Spring boot 中的 統一異常處理
阿新 • • 發佈:2021-02-07
技術標籤:Java
用 spring boot 開發 Java Web 專案,在 Controller 層處理使用者提交的請求時,難免會遇到異常。因此學習 統一的處理 Controller 層中出現的異常是有必要。
統一異常處理:
- 全域性異常處理
- 特定異常處理
- 自定義異常處理
主要程式碼
測試的 Controller
package top.leeti.controller;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import top.leeti.entity.R;
import top.leeti.exception.MyException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@RestController
public class IndexController {
@ApiOperation("正常測試的 uri")
@GetMapping ("test")
public R test() {
return R.ok();
}
@ApiOperation("測試全域性異常的 uri")
@GetMapping("globalError")
public R testGlobalError() {
// 丟擲: IndexOutOfBoundsException
// 並被全域性異常處理器捕獲
List<String> list = new ArrayList< >(Arrays.asList("a"));
list.get(3);
return R.ok();
}
@ApiOperation("測試特定異常的 uri")
@GetMapping("specialError")
public R testSpecialError() {
// 丟擲: ArithmeticException
// 並被 ArithmeticException 異常處理器捕獲
int ans = 9 / 0;
return R.ok();
}
@ApiOperation("測試自定義異常的 uri")
@GetMapping("mineError")
public R testMineError() throws MyException {
// 丟擲: MyException
// 並被 MyException 異常處理器捕獲
throw new MyException();
}
}
測試的異常處理器
package top.leeti.handler;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.leeti.entity.R;
import top.leeti.exception.MyException;
@RestControllerAdvice
public class TestExceptionHandler {
@ExceptionHandler(Exception.class)
public R error(Exception e) {
e.printStackTrace();
return R.error().message("執行出現了全域性異常處理......");
}
@ExceptionHandler(ArithmeticException.class)
public R error(ArithmeticException e) {
e.printStackTrace();
return R.error().message("執行出現了 ArithmeticException 異常處理......");
}
@ExceptionHandler(MyException.class)
public R error(MyException e) {
e.printStackTrace();
return R.error().message("執行出現了 MyException 異常處理......");
}
}
開始測試
啟動專案
依次輸入 url,並觀察返回的結果:
- http://localhost:8000/test
- http://localhost:8000/globalError
- http://localhost:8000/specialError
- http://localhost:8000/mineError
至此,Spring boot 中的 統一異常處理 結束了。
需要說明的是:
統一異常處理的原理是 spring 的 ()面向切面程式設計
全域性異常能匹配沒有特殊說明(即單獨處理的異常)的全部異常。