1. 程式人生 > 程式設計 >SpringBoot處理全域性統一異常的實現

SpringBoot處理全域性統一異常的實現

在後端發生異常或者是請求出錯時,前端通常顯示如下

Whitelabel Error Page
This application has no explicit mapping for /error,so you are seeing this as a fallback.

Fri Jun 07 15:38:07 CST 2019
There was an unexpected error (type=Not Found,status=404).
No message available

對於使用者來說非常不友好。

本文主要講解如何在SpringBoot應用中使用統一異常處理。

實現方式

  • 第一種:使用@ControllerAdvice和@ExceptionHandler註解
  • 第二種: 使用ErrorController類來實現。

第一種:使用@ControllerAdvice和@ExceptionHandler註解

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

  @ResponseBody
  @ExceptionHandler(NullPointerException.class)
  public BaseResult globalException(HttpServletResponse response,NullPointerException ex){


    log.info("GlobalExceptionHandler...");
log.info("錯誤程式碼:" + response.getStatus());
BaseResult result = new WebResult(WebResult.RESULT_FAIL,"request error:"+response.getStatus(),"GlobalExceptionHandler:"+ex.getMessage());
    return result;
}

}

註解@ControllerAdvice表示這是一個控制器增強類,當控制器發生異常且符合類中定義的攔截異常類,將會被攔截。

可以定義攔截的控制器所在的包路徑

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {
  @AliasFor("basePackages")
  String[] value() default {};

  @AliasFor("value")
  String[] basePackages() default {};

  Class<?>[] basePackageClasses() default {};

  Class<?>[] assignableTypes() default {};

  Class<? extends Annotation>[] annotations() default {};
}

註解ExceptionHandler定義攔截的異常類

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
  Class<? extends Throwable>[] value() default {};
}

第二種: 使用ErrorController類來實現。

系統預設的錯誤處理類為BasicErrorController,將會顯示如上的錯誤頁面。

這裡編寫一個自己的錯誤處理類,上面預設的處理類將不會起作用。

getErrorPath()返回的路徑伺服器將會重定向到該路徑對應的處理類,本例中為error方法。

@Slf4j
@RestController
public class HttpErrorController implements ErrorController {

  private final static String ERROR_PATH = "/error";

  @ResponseBody
  @RequestMapping(path = ERROR_PATH )
  public BaseResult error(HttpServletRequest request,HttpServletResponse response){
    log.info("訪問/error" + " 錯誤程式碼:" + response.getStatus());
    BaseResult result = new WebResult(WebResult.RESULT_FAIL,"HttpErrorController error:"+response.getStatus());
return result;
  }
  @Override
  public String getErrorPath() {
    return ERROR_PATH;
  }
}

測試

以上定義了一個統一的返回類BaseResult,方便前端進行處理。

package com.microblog.common.result;

import java.io.Serializable;


public class BaseResult implements Serializable {

  private static final long serialVersionUID = 1L;

  public static final int RESULT_FAIL = 0;
  public static final int RESULT_SUCCESS = 1;

  //返回程式碼
  private Integer code;

  //返回訊息
  private String message;

  //返回物件
  private Object data;

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

  public BaseResult(Integer code,String message,Object object) {
    this.code = code;
    this.message = message;
    this.data = object;
  }


  public Integer getCode() {
    return code;
  }

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

  public String getMessage() {
    return message;
  }

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

  public Object getData() {
    return data;
  }

  public void setData(Object data) {
    this.data = data;
  }
}

編寫一個測試控制器

@Slf4j
@RestController
@RequestMapping("/user")
public class TestController {

  @RequestMapping("/info1")
  public String test(){
   log.info("/user/info1");

   throw new NullPointerException("TestController have exception");

  }
}

1.發出一個錯誤的請求,也就是沒有對應的處理類。

從返回可以看到是由HttpErrorController類處理

{"code":0,"message":"HttpErrorController error:404","data":null}

2.發出一個正常的請求(TestController的test()處理),處理類中丟擲空異樣

從返回中可以看出是由GlobalExceptionHandler類處理

{"code":0,"message":"request error:200","data":"GlobalExceptionHandler:TestController have exception"}

區別

1.註解@ControllerAdvice方式只能處理控制器丟擲的異常。此時請求已經進入控制器中。

2.類ErrorController方式可以處理所有的異常,包括未進入控制器的錯誤,比如404,401等錯誤

3.如果應用中兩者共同存在,則@ControllerAdvice方式處理控制器丟擲的異常,類ErrorController方式未進入控制器的異常。

4.@ControllerAdvice方式可以定義多個攔截方法,攔截不同的異常類,並且可以獲取丟擲的異常資訊,自由度更大。

到此這篇關於SpringBoot處理全域性統一異常的實現的文章就介紹到這了,更多相關SpringBoot 全域性統一異常內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!