@ExceptionHandler 表示攔截異常
- @ControllerAdvice 是 controller 的一個輔助類,最常用的就是作爲全局異常處理的切面類
- @ControllerAdvice 可以指定掃描範圍
- @ControllerAdvice 約定了幾種可行的返回值,如果是直接返回 model 類的話,需要使用 @ResponseBody 進行 json 轉換
- 返回 String,表示跳到某個 view
- 返回 modelAndView
- 返回 model + @ResponseBody
package com.xyt.springboot.controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionHandler {
//@ControllerAdvice異常切面類
@ExceptionHandler(RuntimeException.class)//RuntimeException運行時的所有意嘗都返回101:系統錯誤
@ResponseBody
public Map<String, Object> exceptionHandler() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("errorCode", "101");
map.put("errorMsg", "系統錯誤!");
return map;
}
}
spring boot配置了全局捕獲異常效果如下
未配置全局異常前
配置全局異常後的效果