异常处理
Spring MVC 异常(仅 MVC)
SystemExceptionHandler 处理 Spring MVC 框架级异常,覆盖参数校验、请求方法不匹配等场景
SystemExceptionHandler
SystemExceptionHandler 是异常处理继承链的最顶层,继承自 PublicExceptionHandler,负责处理 Spring MVC 框架在请求处理过程中抛出的异常。项目中自定义异常处理器应继承此类。
继承关系
JavaBaseExceptionHandler
└── PublicExceptionHandler
└── SystemExceptionHandler ← 当前层级(推荐继承)处理的异常类型
字段
类型
处理器结构
@RestControllerAdvice
public class SystemExceptionHandler extends PublicExceptionHandler {
// 请求方法不支持
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResponseEntity<BaseResponse<Void>> handleMethodNotSupported(
HttpRequestMethodNotSupportedException e) {
return ResultUtil.error(
ErrorCode.REQUEST_METHOD_NOT_ALLOWED, e.getMessage(), null
);
}
// 参数校验失败(@Valid)
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<BaseResponse<Void>> handleValidationException(
MethodArgumentNotValidException e) {
return ResultUtil.error(
ErrorCode.PARAMETER_ERROR, e.getMessage(), null
);
}
// 请求体无法解析
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<BaseResponse<Void>> handleNotReadable(
HttpMessageNotReadableException e) {
return ResultUtil.error(
ErrorCode.PARAMETER_ERROR, e.getMessage(), null
);
}
// ... 其他异常处理方法
}典型场景
参数校验失败
当使用 @Valid 进行参数校验时:
@PostMapping("/register")
public ResponseEntity<BaseResponse<Void>> register(
// @Valid 触发 Bean Validation
@Valid @RequestBody RegisterDTO dto) {
userService.register(dto);
return ResultUtil.success("注册成功");
}public record RegisterDTO(
@NotBlank(message = "用户名不能为空")
String username,
@Email(message = "邮箱格式不正确")
String email,
@Size(min = 8, message = "密码长度不得少于 8 位")
String password
) {}校验失败时自动返回:
{
"context": "550e8400-e29b-41d4-a716-446655440000",
"output": "PARAMETER_ERROR",
"code": 40000,
"message": null,
"errorMessage": "用户名不能为空",
"duration": 5,
"data": null
}请求方法不匹配
当 POST 接口收到 GET 请求时:
{
"context": "550e8400-e29b-41d4-a716-446655440000",
"output": "REQUEST_METHOD_NOT_ALLOWED",
"code": 40500,
"message": null,
"errorMessage": "Request method 'GET' is not supported",
"duration": 2,
"data": null
}资源未找到
当请求的 URL 不存在时:
{
"context": "550e8400-e29b-41d4-a716-446655440000",
"output": "PAGE_NOT_FOUND",
"code": 40403,
"message": null,
"errorMessage": "No static resource found",
"duration": 1,
"data": null
}