全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-18 7 分钟 ✍️ juanwangdev

Spring Boot @ControllerAdvice与@ExceptionHandler

@ControllerAdvice配合@ExceptionHandler是Spring MVC提供的全局异常处理方案,实现跨Controller的统一异常捕获。

@ControllerAdvice注解

基本用法

Java
@ControllerAdvice
public class GlobalExceptionHandler {
    // 全局异常处理方法
}

限定作用范围

Java
// 限定Controller包路径
@ControllerAdvice("com.example.web")

// 限定注解类型
@ControllerAdvice(annotations = RestController.class)

// 限定具体类
@ControllerAdvice(assignableTypes = {UserController.class, OrderController.class})

@ExceptionHandler注解

基本用法

Java
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException e) {
        return ResponseEntity.status(500).body(e.getMessage());
    }

    @ExceptionHandler({NullPointerException.class, IllegalArgumentException.class})
    public ResponseEntity<String> handleMulti(Exception e) {
        return ResponseEntity.badRequest().body(e.getMessage());
    }
}

方法签名

Java
// 支持的参数类型
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handle(
    Exception e,                    // 异常对象
    HttpServletRequest request,     // 请求对象
    HttpServletResponse response,   // 响应对象
    WebRequest webRequest          // Web请求对象
) { ... }

// 支持的返回类型
@ExceptionHandler(Exception.class)
public String handle(Exception e, Model model) { return "error"; }  // 视图名

@ExceptionHandler(Exception.class)
@ResponseBody
public Result handle(Exception e) { return Result.fail(e.getMessage()); }  // JSON

@ExceptionHandler(Exception.class)
public ResponseEntity<Result> handle(Exception e) { return ResponseEntity.ok(Result.fail()); }

@RestControllerAdvice

Java
@RestControllerAdvice = @ControllerAdvice + @ResponseBody

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Result handle(Exception e) {
        return Result.fail(e.getMessage());  // 自动序列化为JSON
    }
}

异常匹配规则

规则说明
精确匹配优先匹配异常类型完全一致的处理方法
父类匹配无精确匹配时,匹配最近父类
多异常声明@ExceptionHandler可声明多个异常类型

同一异常只能被一个@ExceptionHandler方法处理,优先匹配最具体的异常类型。

要点总结

  • @ControllerAdvice定义全局异常处理类
  • @ExceptionHandler标注异常处理方法
  • @RestControllerAdvice等同于@ControllerAdvice+@ResponseBody
  • 可通过属性限定作用范围
  • 异常匹配遵循最近父类原则

📝 发现内容有误?点击此处直接编辑

← 上一篇 Spring Boot 404等容器级异常处理
下一篇 → Spring Boot 全局异常处理原理
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库