SpringBoot 定義全局捕獲異常類(lèi) @RestControllerAdvice 注解

Spring 3.2中,新增了@ControllerAdvice、@RestControllerAdvice 注解,可以用于定義@ExceptionHandler、@InitBinder、@ModelAttribute

注解@ControllerAdvice的類(lèi)可以擁有@ExceptionHandler, @InitBinder@ModelAttribute注解的方法, 并且這些方法會(huì)被應(yīng)用到控制器類(lèi)層次的所有@RequestMapping方法上

@RestControllerAdvice@ControllerAdvice 的區(qū)別就相當(dāng)于 @RestController@Controller的區(qū)別

編寫(xiě)自定義異常類(lèi)

spring boot 默認(rèn)情況下會(huì)映射到 /error 進(jìn)行異常處理,但是提示并不十分友好,通過(guò)自定義異常處理,提供友好展示

import lombok.Data;

/**
 * @ClassName: CustomerException
 * @Description: 自定義異常類(lèi)
 * Spring 對(duì)于 RuntimeException類(lèi)的異常才會(huì)進(jìn)行事務(wù)回滾,所以我們一般自定義異常都繼承該異常類(lèi)
 * @Author mac
 * @Date 2019-06-15 21:10
 **/
@Data
class CustomerException extends RuntimeException {

    /**
     * 返回標(biāo)示碼
     */
    private String code;

    /**
     * 返回詳細(xì)信息
     */
    private String msg;

    public CustomerException(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

定義全局返回類(lèi)

import lombok.Data;

/**
 * @ClassName: Result
 * @Description: 全局返回類(lèi)
 * @Author mac
 * @Date 2019-06-15 21:17
 **/
@Data
public class Result {

    private String code;
    private String message;

    public Result() {}

    public Result(String code, String message) {
        this.code = code;
        this.message = message;
    }
}

定義全局捕獲異常類(lèi)

import com.guahao.convention.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: MyControllerAdvice
 * @Description: 全局捕獲異常類(lèi)
 * @Author mac
 * @Date 2019-06-15 21:20
 **/
@RestControllerAdvice
public class MyControllerAdvice {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 應(yīng)用到所有@RequestMapping, 在其執(zhí)行之前初始化數(shù)據(jù)綁定器
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) { }

    /**
     * 把值綁定到Model中, 使全局@RequestMapping可以獲取該值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "MaLongT");
    }

    /**
     * 指定攔截異常的類(lèi)型
     * 自定義瀏覽器請(qǐng)求返回狀態(tài)碼
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler({CustomerException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result customerException(HttpServletRequest request, CustomerException ex) {
        // false 表示異常信息不是系統(tǒng)類(lèi)異常
        logThrowable(false, request, ex);
        return new Result(ex.getCode(), ex.getMsg());
    }

    private void logThrowable(boolean error, HttpServletRequest request, Throwable throwable) {
        if (error) {
            this.logger.error("[" + request.getMethod() + "] " + request.getRequestURI() + (StringUtils.isEmpty(request.getQueryString()) ? "" : "?" + request.getQueryString()) + " ", throwable);
        } else if (this.logger.isInfoEnabled()) {
            this.logger.info("[" + request.getMethod() + "] " + request.getRequestURI() + (StringUtils.isEmpty(request.getQueryString()) ? "" : "?" + request.getQueryString()));
        }
    }

}

測(cè)試 Controller 層訪問(wèn)方法

@ModelAttribute:在Model上設(shè)置的值,對(duì)于所有被@RequestMapping注解的方法中,都可以通過(guò) @ModelAttribute("author")獲取,如下:

// 使用ModelMap也是一樣效果 modelMap.get("author")
@GetMapping("/test/exception")
public String test(@ModelAttribute("author") String author) {
  throw new CustomerException("500", "系統(tǒng)發(fā)生500異常, 編寫(xiě)異常罪魁禍?zhǔn)? " + author);
}

啟動(dòng)項(xiàng)目,瀏覽器或者 postman 訪問(wèn)localhost:8080/test/exception, 返回信息為:

{
    "code": "500",
    "message": "系統(tǒng)發(fā)生500異常, 編寫(xiě)異常作者: MaLongT"
}
最后編輯于
?著作權(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)容

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