@exceptionhandler是spring boot中处理控制器层异常的核心注解,用于针对特定异常类型定制响应逻辑;可单捕获某类异常、数组形式处理多异常,或配合@controlleradvice实现全局异常处理。

在 Spring Boot 中,@ExceptionHandler 是处理控制器层异常的核心注解,它能让你针对特定异常类型定制响应逻辑,避免全局崩溃或返回不友好的错误信息。
只捕获某一种异常(最常用)
在 @Controller 或 @RestController 类中,用 @ExceptionHandler(YourException.class) 声明一个方法,该方法就只响应这种异常:
- 方法参数可以接收对应异常对象(如
MyBusinessException e),也可加HttpServletRequest、HttpServletResponse等上下文对象 - 返回值可以是字符串(视图名)、
ModelAndView、@ResponseBody对象(如ResponseEntity<string></string>或自定义 JSON 结构) - 异常必须是实际抛出的类型,或其子类;父类异常无法匹配子类抛出的实例(除非你显式声明父类)
示例:
@RestController
public class OrderController {
@GetMapping("/order/{id}")
public Order getOrder(@PathVariable Long id) {
if (id handleIllegalArgument(IllegalArgumentException e) {
return ResponseEntity.badRequest().body("参数错误:" + e.getMessage());
}
}
在一个方法里处理多个异常类型
用数组形式传入多个异常类,方法体统一处理:
@ExceptionHandler({IllegalArgumentException.class, NullPointerException.class})
public ResponseEntity<string> handleBadInput(Exception e) {
return ResponseEntity.badRequest().body("输入异常:" + e.getClass().getSimpleName());
}</string>
注意:这种方式适合响应逻辑高度相似的异常;若需差异化处理(比如不同状态码、不同字段),建议拆成多个独立的 @ExceptionHandler 方法。
配合 @ControllerAdvice 实现全局异常处理
如果希望整个应用共享一套异常处理规则,把 @ExceptionHandler 方法移到带 @ControllerAdvice 的类中:
-
@ControllerAdvice默认作用于所有@Controller/@RestController - @RestControllerAdvice(等价于
@ControllerAdvice + @ResponseBody),让返回值直接序列化为 JSON - basePackages 或
annotations属性限定生效范围
示例:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<errorresponse> handleUserNotFound(UserNotFoundException e) {
return ResponseEntity.status(404).body(new ErrorResponse("用户不存在", e.getMessage()));
}
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<errorresponse> handleTypeMismatch(MethodArgumentTypeMismatchException e) {
return ResponseEntity.badRequest()
.body(new ErrorResponse("参数类型错误", String.format("期望 %s,但得到 %s",
e.getRequiredType().getSimpleName(), e.getValue())));
}
}</errorresponse></errorresponse>
优先级与继承关系要注意
Spring 按照“最具体到最宽泛”匹配异常处理器:
- 如果同时存在
@ExceptionHandler(NullPointerException.class)和@ExceptionHandler(RuntimeException.class),抛出NullPointerException时只会进入前者 - 若没有精确匹配的方法,会向上查找父类异常的处理器(例如抛出
CustomException extends RuntimeException,而只有@ExceptionHandler(RuntimeException.class),就会命中) - 同一类中多个
@ExceptionHandler方法,Spring 自动选择最具体的那个,无需手动排序
不复杂但容易忽略。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











