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());
}
}
属性说明
| 属性 | 类型 | 说明 |
|---|---|---|
| value | Class[] | 要捕获的异常类型 |
捕获多种异常
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 实现全局异常处理
📝 发现内容有误?点击此处直接编辑