Java Spring Boot中统一异常处理需结合自定义异常类、@ControllerAdvice和@ExceptionHandler:定义继承RuntimeException的BizException含code/message;用@RestControllerAdvice全局捕获并返回统一ApiResponse格式;业务层直接throw,无需try-catch。

在 Java 框架中(如 Spring Boot),自定义异常要实现统一捕获,核心是结合 自定义异常类 + @ControllerAdvice + @ExceptionHandler 三者配合,避免每个 Controller 里重复 try-catch。
定义自定义异常类
继承 RuntimeException(运行时异常,无需强制 try-catch)或 Exception(检查异常,需显式处理),通常推荐前者。添加错误码、消息、可选的业务字段:
public class BizException extends RuntimeException {
private final int code;
public BizException(int code, String message) {
super(message);
this.code = code;
}
public int getCode() {
return code;
}
}
全局异常处理器(@ControllerAdvice)
创建一个被 @ControllerAdvice 标记的类,它会拦截所有 @RestController 和 @Controller 中抛出的异常:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BizException.class)
public ResponseEntity<ApiResponse> handleBizException(BizException e) {
return ResponseEntity.status(400).body(
new ApiResponse(e.getCode(), e.getMessage(), null)
);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse> handleOtherException(Exception e) {
return ResponseEntity.status(500).body(
new ApiResponse(500, "系统内部错误", null)
);
}
}
注意:@RestControllerAdvice = @ControllerAdvice + @ResponseBody,适合返回 JSON。
立即学习“Java免费学习笔记(深入)”;
统一响应结构(可选但推荐)
让所有接口返回格式一致,比如:
public class ApiResponse<T> {
private int code;
private String message;
private T data;
public ApiResponse(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
// getter/setter 省略
}
在业务中抛出自定义异常
Controller 或 Service 层直接 throw,框架自动交给全局处理器:
@GetMapping("/user/{id}")
public User getUser(@PathVariable Long id) {
if (id <= 0) {
throw new BizException(4001, "用户ID非法");
}
return userService.findById(id);
}
不需要 try-catch,异常会穿透到 GlobalExceptionHandler。
不复杂但容易忽略:确保自定义异常类在包扫描范围内;Spring Boot 默认已启用 @ControllerAdvice,无需额外配置;若用 WebMvcConfigurer 自定义配置,需确认未覆盖默认异常处理机制。


















