异常处理
公共业务异常
PublicExceptionHandler 处理框架定义的业务级异常,覆盖认证、权限、参数校验等场景
公共业务异常
PublicExceptionHandler 继承自 JavaBaseExceptionHandler,负责处理框架层面定义的业务异常。这些异常通常由业务代码主动抛出,用于表达特定的业务错误语义。
MVC 与 WebFlux
本文档描述的异常映射表在 MVC 和 WebFlux 中完全一致。主要差异是返回类型:
- MVC:
ResponseEntity<BaseResponse<T>> - WebFlux:
Mono<ResponseEntity<BaseResponse<T>>>
继承关系
JavaBaseExceptionHandler
└── PublicExceptionHandler ← 当前层级
└── SystemExceptionHandler处理的异常类型
字段
类型
BusinessException 使用
BusinessException 是最常用的业务异常,支持自定义 ErrorCode 和错误消息:
@Service
public class UserService {
public UserVO getUserById(Long id) {
UserEntity user = userMapper.selectById(id);
if (user == null) {
// 抛出业务异常,指定错误码和错误消息
throw new BusinessException(
"用户不存在", ErrorCode.PAGE_NOT_FOUND
);
}
return convertToVO(user);
}
public void updateEmail(Long id, String email) {
if (!isValidEmail(email)) {
throw new BusinessException(
"邮箱格式不正确", ErrorCode.PARAMETER_ERROR
);
}
// 业务逻辑...
}
}响应示例
抛出 BusinessException("用户不存在", ErrorCode.PAGE_NOT_FOUND) 时:
{
"context": "550e8400-e29b-41d4-a716-446655440000",
"output": "PAGE_NOT_FOUND",
"code": 40403,
"message": null,
"errorMessage": "用户不存在",
"duration": 8,
"data": null
}HTTP 状态码为 404(40403 / 100)。
异常选择指南
| 场景 | 推荐异常 |
|---|---|
| 通用业务错误 | BusinessException |
| 资源不存在 | PageNotFoundedException 或 BusinessException("...", PAGE_NOT_FOUND) |
| 参数校验失败 | CheckFailureException |
| 用户未登录/令牌过期 | UserAuthenticationException |
| 权限不足 | NoPermissionException |
| 开发阶段的逻辑标记 | DeveloperException |