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

Spring MVC @ExceptionHandler注解

@ExceptionHandler 用于在控制器内声明异常处理方法,捕获特定异常并返回统一响应。

基本用法

Java
@RestController
public class UserController {

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
        if (id == null) {
            throw new IllegalArgumentException("ID不能为空");
        }
        return userService.findById(id);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public Result<String> handleIllegalArgument(IllegalArgumentException ex) {
        return Result.fail(400, ex.getMessage());
    }
}

属性说明

属性类型说明
valueClass[]要捕获的异常类型

捕获多种异常

Java
@ExceptionHandler({NullPointerException.class, IllegalArgumentException.class})
public Result<String> handleBadRequest(Exception ex) {
    return Result.fail(400, "请求参数错误");
}

返回值类型

返回类型用途
ModelAndView返回错误页面
String返回视图名
ResponseEntity返回状态码和响应体
Object配合 @ResponseBody 返回 JSON

获取异常信息

Java
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleException(Exception ex, HttpServletRequest request) {
    Map<String, Object> body = new HashMap<>();
    body.put("timestamp", System.currentTimeMillis());
    body.put("status", 500);
    body.put("error", ex.getClass().getSimpleName());
    body.put("message", ex.getMessage());
    body.put("path", request.getRequestURI());
    return ResponseEntity.status(500).body(body);
}

与 @ControllerAdvice 配合

@ExceptionHandler 只能处理当前控制器内的异常,配合 @ControllerAdvice 可实现全局异常处理:

Java
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusiness(BusinessException ex) {
        return Result.fail(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception ex) {
        return Result.fail(500, "系统异常");
    }
}

@ExceptionHandler 方法不能捕获其他 @ExceptionHandler 方法抛出的异常。

要点总结

  • @ExceptionHandler 声明异常处理方法
  • 可捕获单个或多个异常类型
  • 只处理当前控制器内的异常
  • 配合 @ControllerAdvice 实现全局异常处理

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

← 上一篇 Spring MVC @Controller注解
下一篇 → Spring MVC @PathVariable注解
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

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

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