1. 程式人生 > >SpringBoot基於@ControllerAdvice配置全域性異常處理

SpringBoot基於@ControllerAdvice配置全域性異常處理

SpringBoot預設全域性異常處理

SpringBoot提供了一個預設的對映:/error,當處理中丟擲異常之後,會轉到請求中處理,並且該請求有一個全域性的錯誤頁面用來展示異常內容。
啟動訪問一個異常的url出現的呈現的頁面情況是這樣的:
這裡寫圖片描述
但是這樣的頁面我們也覺得不太友好,想自己設定異常的處理頁面或者是展示異常處理資訊,這時候我們就要用到@ControllerAdvice定義統一處理的異常處理類,而不是在每一個Controller中逐個定義。@ExceptionHandler用來定義函式針對的異常型別。

自定義全域性處理異常

1.Exception物件和請求url對映到error.html中:

@ControllerAdvice
public class GlobalExceptionHandler {
   @ExceptionHandler(value = Exception.class)
    public String exceptionHandle(HttpServletRequest request, Exception e){
       return "error";
    }
}

springboot引入thymeleaf,在application.propertities設定:

spring.thymeleaf.cache=false
spring.thymeleaf
.servlet.content-type=text/html spring.thymeleaf.enabled=true spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.mode=HTML5 spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html

在src/resource/templates路徑下建立error.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta
charset="UTF-8">
<title>錯誤介面</title> </head> <body> 您好,當前訪問地址出錯! </body> </html>

最後輸出一個異常的路徑如下圖:
這裡寫圖片描述

2.Exception物件和請求url返回json物件:


  • 配置全域性異常處理
  • 全域性異常物件
  • 返回錯誤結果封裝

配置全域性異常處理:

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)  //處理所有的異常
    public Result<String> exceptionHandle(HttpServletRequest request, Exception e){
        e.printStackTrace();
        //將異常進行分類,不同的異常進行不同的處理
        if(e instanceof GlobalException){
            GlobalException ex=(GlobalException) e;
            return Result.error(ex.getCm());
        }else if(e instanceof BindException){
            BindException ex = (BindException)e;
            List<ObjectError> errors = ex.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return Result.error(CodeMessage.BIND_ERROR.fillArgs(msg));
        }else {
            return Result.error(CodeMessage.SERVER_ERROR);
        }
    }
}
public class GlobalException  extends RuntimeException{
    private static final long serialVersionUID = 1L;
    private CodeMessage cm;
    public GlobalException(CodeMessage cm){
        super(cm.toString());
        this.cm=cm;
    }
    public CodeMessage getCm(){
        return cm;
    }
}

異常返回資訊封裝CodeMessage:

public class CodeMessage {
    private int code;
    private String message;
    //通用異常:
    public  static CodeMessage SUCCESS=new CodeMessage(0,"success");
    public  static  CodeMessage SERVER_ERROR=new CodeMessage(500,"服務端異常");
    public  static  CodeMessage  MOBILE_NOT_EXIST=new CodeMessage(400,"手機不存在");
    public  static  CodeMessage  PASSWORD_ERROR=new CodeMessage(401,"密碼不正確");
    public static CodeMessage BIND_ERROR = new CodeMessage(500101, "引數校驗異常:%s");

    public int getCode() {
        return code;
    }

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

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return "CodeMessage{" +
                "code=" + code +
                ", message='" + message + '\'' +
                '}';
    }

    public CodeMessage fillArgs(Object... args) {
        int code = this.code;
        String message = String.format(this.message, args);
        return new CodeMessage(code, message);
    }
}

總結:
希望對你有幫助,感謝瀏覽!