Java 后端 / 系统课时
集中处理业务异常
集中处理业务异常
本课把控制器、参数校验和业务层抛出的异常统一收口到 @RestControllerAdvice,让接口始终返回稳定的错误结构。完成后,控制器只负责表达业务流程,异常分类、日志记录和 HTTP 状态映射由全局处理器集中完成。
学习目标
- 区分参数校验异常、业务异常和未预期系统异常
- 使用
@RestControllerAdvice与@ExceptionHandler统一生成错误响应 - 验证异常是否被正确映射为状态码和响应体
为什么要集中处理异常
在每个控制器里重复 try-catch,会把业务代码和错误协议耦合在一起。新增异常类型时,还容易出现不同接口返回结构、状态码或文案不一致的问题。
更合理的职责划分是:业务代码发现问题后抛出明确异常;全局异常处理器根据异常类型决定错误码、HTTP 状态和客户端可见信息;系统异常只记录必要上下文,不把堆栈或数据库细节暴露给客户端。

定义统一错误对象和业务异常
以下为片段示例,放入已包含 spring-boot-starter-web 与 spring-boot-starter-validation 的 Spring Boot 3 项目中。错误对象只保留客户端需要的字段,业务异常携带稳定错误码和安全文案。
package com.example.demo.error;
import java.time.Instant;
public record ApiError(
String code,
String message,
String path,
Instant timestamp
) {
}package com.example.demo.error;
public class BusinessException extends RuntimeException {
private final String code;
public BusinessException(String code, String message) {
super(message);
this.code = code;
}
public String getCode() {
return code;
}
}业务层发现“邮箱已被占用”时,可以直接执行 throw new BusinessException("USER_EMAIL_EXISTS", "邮箱已被占用");。不要在异常中放入 SQL、表名或内部主键等实现细节。
编写全局异常处理器
全局处理器按“最具体异常优先、兜底异常最后”的顺序声明。参数校验错误返回 400 Bad Request,业务冲突返回 409 Conflict,未预期错误返回 500 Internal Server Error。
package com.example.demo.error;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.time.Instant;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log =
LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleValidation(
MethodArgumentNotValidException exception,
HttpServletRequest request) {
String message = exception.getBindingResult()
.getFieldErrors()
.stream()
.findFirst()
.map(error -> error.getField() + " " + error.getDefaultMessage())
.orElse("请求参数不合法");
return build(
HttpStatus.BAD_REQUEST,
"VALIDATION_FAILED",
message,
request.getRequestURI()
);
}
@ExceptionHandler(BusinessException.class)
public ResponseEntity<ApiError> handleBusiness(
BusinessException exception,
HttpServletRequest request) {
return build(
HttpStatus.CONFLICT,
exception.getCode(),
exception.getMessage(),
request.getRequestURI()
);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiError> handleUnexpected(
Exception exception,
HttpServletRequest request) {
log.error("Unhandled exception, path={}",
request.getRequestURI(), exception);
return build(
HttpStatus.INTERNAL_SERVER_ERROR,
"INTERNAL_ERROR",
"服务暂时不可用,请稍后重试",
request.getRequestURI()
);
}
private ResponseEntity<ApiError> build(
HttpStatus status,
String code,
String message,
String path) {
ApiError body = new ApiError(
code,
message,
path,
Instant.now()
);
return ResponseEntity.status(status).body(body);
}
}这里不捕获异常后继续返回成功状态。错误响应的 HTTP 状态必须与失败性质一致,否则网关、监控和客户端重试策略都会被误导。
触发并验证三类异常
假设 POST /users 使用 @Valid 校验邮箱,并在邮箱重复时抛出 BusinessException。先发送非法参数:
curl -i -X POST http://localhost:<PORT>/users -H "Content-Type: application/json" -d '{"email":"not-an-email"}'预期结果:
HTTP/1.1 400
Content-Type: application/json
{"code":"VALIDATION_FAILED","message":"email 邮箱格式不正确","path":"/users","timestamp":"<TIME>"}再发送已存在的邮箱:
curl -i -X POST http://localhost:<PORT>/users -H "Content-Type: application/json" -d '{"email":"used@example.com"}'预期结果:
HTTP/1.1 409
Content-Type: application/json
{"code":"USER_EMAIL_EXISTS","message":"邮箱已被占用","path":"/users","timestamp":"<TIME>"}实际端口、时间和校验文案可能不同。验证重点是状态码、错误码、路径和响应结构保持稳定。
处理边界与常见错误
@RestControllerAdvice 只负责 Web 层响应转换,不应在其中补做核心业务。业务异常应表示可预期、可解释的失败;真正未知的异常必须记录完整堆栈,但客户端只看到通用提示。
不要用一个 Exception 处理器覆盖全部语义,也不要把异常信息原样返回。对于认证、权限、资源不存在等场景,应继续增加更具体的异常类型和状态映射。