在日常开发中,异常处理是后端服务稳定性的重要一环。如果没有统一处理,代码里就会充斥大量 try-catch,不仅冗余,还不利于维护。
本文介绍如何在 Spring Boot 中实现优雅的全局异常处理。
1. 使用 @RestControllerAdvice + @ExceptionHandler
Spring 提供了全局异常处理机制,可以集中捕获并返回统一的响应格式。
示例代码:
@RestControllerAdvice
public class GlobalExceptionHandler {
// 处理业务异常
@ExceptionHandler(BusinessException.class)
public ResponseEntity<?> handleBusinessException(BusinessException e) {
return ResponseEntity.badRequest().body(new ErrorResponse(e.getCode(), e.getMessage()));
}
// 处理系统异常
@ExceptionHandler(Exception.class)
public ResponseEntity<?> handleException(Exception e) {
return ResponseEntity.status(500).body(new ErrorResponse("500", "服务器内部错误"));
}
}
2. 定义统一返回体
@Data
@AllArgsConstructor
public class ErrorResponse {
private String code;
private String message;
}
3. 好处
- 统一格式:前端能轻松解析错误信息
- 减少重复:不用到处写
try-catch - 可扩展:方便添加自定义异常