Springboot 自定義異常

當(dāng)我們使用springboot 寫(xiě) restful接口時(shí) , 不希望錯(cuò)誤信息返回一個(gè)Html格式. 例如404時(shí), 返回如圖:

i404錯(cuò)誤示例

顯得非常的不友好 , 接下來(lái), 我們就嘗試下自定義異常.

禁用默認(rèn)異常處理

在配置文件(application.yml)中, 添加如下配置

spring:
  mvc:
    throw-exception-if-no-handler-found: true
  resources:
    add-mappings: false

添加全局異常處理控制器

package club.maoyupeng.scm.base.web.controller;

import club.maoyupeng.utils.result.ResponseModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;


/**
 * <b>標(biāo)題:    </b><br />
 * <pre>
 * </pre>
 *
 * @author 毛宇鵬
 * @date 創(chuàng)建于 下午1:56 2018/9/27
 */
@ControllerAdvice
public class ErrorController  {
    protected final ResultUtil result = new ResultUtil();

    private static final Logger log = LogManager.getLogger(ErrorController.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseModel systemException(Exception e) {
        log.error("System error");
        return result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseModel methodNotSupported(NoHandlerFoundException e) {
        log.error("method not found : 404");
        return result.error(HttpStatus.NOT_FOUND.value(), e.getMessage());
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public ResponseModel methodNotSupported(HttpRequestMethodNotSupportedException e) {
        log.error("method not support : 405");
        return result.error(HttpStatus.METHOD_NOT_ALLOWED.value(), e.getMessage());
    }

    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public ResponseModel mediaTypeNotSupported(HttpMediaTypeNotSupportedException e) {
        log.error("media type not support : 415");
        return result.error(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), e.getMessage());
    }

    @ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    public ResponseModel mediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException e) {
        log.error("media type not acceptable : 406");
        return result.error(HttpStatus.NOT_ACCEPTABLE.value(), e.getMessage());
    }
}

ResultUtil 參考代碼:
主要是將錯(cuò)誤碼和錯(cuò)誤信息封裝成一個(gè)json對(duì)象, 例如: {code: 400, msg: '錯(cuò)誤信息'}

public ResponseModel error(int errorCode, String message) {
    ResponseModel model = new ResponseModel();
    super.setErrorMessage(model, errorCode, message);
    return model;
}

結(jié)果

改造前
i改造后
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,500評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,253評(píng)論 6 342
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,930評(píng)論 1 92
  • 個(gè)人專題目錄[http://www.itdecent.cn/u/2a55010e3a04] 一、Spring B...
    Java及SpringBoot閱讀 2,881評(píng)論 1 25
  • 目標(biāo) 一、早睡早起,堅(jiān)持每天早上閱讀; 第二、堅(jiān)持早起適量運(yùn)動(dòng); 第三、踐行番茄工作法。 周檢視: 第一項(xiàng):早起堅(jiān)...
    觀滄海_32bb閱讀 113評(píng)論 0 0

友情鏈接更多精彩內(nèi)容