
本文详解 Spring Boot REST API 中如何正确配置全局异常处理器,解决 @ExceptionHandler 无法捕获并返回自定义错误信息的问题,涵盖注解位置、方法签名规范及最佳实践。
本文详解 spring boot rest api 中如何正确配置全局异常处理器,解决 `@exceptionhandler` 无法捕获并返回自定义错误信息的问题,涵盖注解位置、方法签名规范及最佳实践。
在 Spring Boot 中,@ExceptionHandler 的使用有严格约定:它不能与 @GetMapping 等请求映射注解共存于同一方法上,且必须定义在 @ControllerAdvice 或 @RestControllerAdvice 类中(而非直接写在 @RestController 内),否则将被忽略——这正是你遇到问题的根本原因。
你当前的代码将 @ExceptionHandler 错误地放在了控制器方法上,并混用了 @GetMapping,导致 Spring 完全不识别该异常处理器,最终回退到默认的 500 响应体(含 timestamp、status、error 等字段),而你的自定义异常消息(如 "Inexistent user 3")从未被序列化输出。
✅ 正确做法是分离关注点:
- 定义业务异常类(推荐继承 RuntimeException,保持非检查异常语义):
public class NotFoundException extends RuntimeException {
public NotFoundException(String message) {
super(message);
}
}
- 创建全局异常处理器类(使用 @RestControllerAdvice 自动适配 REST 接口):
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND) // 语义更准确:资源不存在应返回 404,非 500
public ErrorResponse handleNotFoundException(NotFoundException e) {
return new ErrorResponse("NOT_FOUND", e.getMessage(), System.currentTimeMillis());
}
}
其中 ErrorResponse 是你自定义的响应结构:
public class ErrorResponse {
private String code;
private String message;
private long timestamp;
public ErrorResponse(String code, String message, long timestamp) {
this.code = code;
this.message = message;
this.timestamp = timestamp;
}
// getters...
}
- 在 Controller 中抛出异常即可(无需手动 try-catch):
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserRepository userRepo;
@GetMapping("userino/{id}")
public User getUserino(@PathVariable Long id) {
return userRepo.findById(id)
.orElseThrow(() -> new NotFoundException("Inexistent user " + id));
}
}
⚠️ 注意事项:
- @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 应改为 HttpStatus.NOT_FOUND(HTTP 404),更符合 REST 语义;滥用 500 会误导客户端认为是服务端故障,而非资源缺失。
- @ExceptionHandler 方法参数必须为对应异常类型(如 NotFoundException e),且不能有路径映射注解;返回值可为任意对象(自动 JSON 序列化)或 ResponseEntity>(用于动态控制状态码与响应头)。
- 若需统一处理所有未捕获异常,可添加 @ExceptionHandler(Exception.class) 作为兜底处理器,但建议按类型精细化处理。
通过以上结构,当访问 /api/userino/3 且用户不存在时,将得到清晰、可控的响应:
{
"code": "NOT_FOUND",
"message": "Inexistent user 3",
"timestamp": 1715872390123
}
这才是专业、可维护的 Spring Boot 异常处理实践。










