1. 程式人生 > >Spring 中全域性異常處理 @ExceptionHandler

Spring 中全域性異常處理 @ExceptionHandler

最近在專案中整理了一些關於 Springboot Spring Exception 處理, 記錄下來也分享給其他需要的人.

學習全域性異常處理之前, 首先我們來了解兩個註解. @ControllerAdvice 和 @ExceptionHandler

@ControllerAdvice : 可以顯式宣告為 Spring beans 或通過類路徑掃描自動檢測.

其實可以理解成 @ControllerAdvice 和 @Component 一樣可以實現依賴注入.

@ExceptionHandler 會接受並處理 @RequestMapping 方法中丟擲的異常. 下面的程式碼就展示了一個定義在 Controller 內部的 @ExceptionHandler 

方法.


@Controller
public class SimpleController {


    @ExceptionHandler(IOException.class)
    @RequestMapping("/test")
    public ResponseEntity<String> handleIOException(IOException ex) {
        
        return responseEntity;
    }
}

當然了,我們說了要做全域性的異常處理, 上面只是處理了一個方法的Exception,這不是我們想要的.全域性Exception看下面


/**
 * @author: ZhangGuihong
 * @Date: 2018/9/19 22:59
 */
@ControllerAdvice
@Slf4j
public class KunlunExceptionHandler {

    // Exception.class 是我們想要捕獲的異常類,根據業務需要也可以換成其他異常類   
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object kunlunExceptionHandler(Exception e) {

        
        // 這裡可以寫一下適合你專案的異常處理  
        return "Samething is wrong!";
    }
}
這樣在 web 專案中所有在 Controller 中丟擲的異常都在在這裡進行處理,我們也就做到了全域性的異常處理.