当前位置:
Spring Boot 全局异常处理及几点注意
机器助手 | 2025-07-13
153人浏览
使用@ControllerAdvice + @ExceptionHandler全局异常处理
示例:
Java配置类:
@ControllerAdvice
public class GlobalExceptionHandleConfig {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map<String, Object> exceptionErrorHandle(Exception e) {
logger.info("异常类型:Exception");
Map<String, Object> res = new HashMap<>();
res.put("code", -1);
res.put("message", e.getMessage());
return res;
}
@ResponseBody
@ExceptionHandler(value = ArithmeticException.class)
public Map<String, Object> arithmeticExceptionErrorHandle(ArithmeticException e) {
logger.info("异常类型:ArithmeticException");
Map<String, Object> res = new HashMap<>();
res.put("code", -1);
res.put("message", e.getMessage());
return res;
}
}
Controller:
@RestController
public class TestController {
@GetMapping("/test")
public String test() {
try {
int i = 1 / 0;
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
}
2.执行exceptionErrorHandle方法
@RestController
public class TestController {
@GetMapping("/test")
public String test() {
// ArithmeticException
int i = 1 / 0;
return "success";
}
}
注: 1.如果同时存在Exception和ArithmeticException异常捕获,执行更为具体的异常处理。
2.在try...catch中抛出异常后,exceptionErrorHandle方法不会执行
