Spring Boot 4 如何映射自定义异常状态码并保留默认 ErrorAttributes?
结论
在保留 Spring Boot 默认 Spring MVC 错误处理配置的前提下,可以在 @ExceptionHandler 中调用 HttpServletResponse.sendError(422, message),由默认 /error 流程生成响应。这样无需在 handler 中构造错误字段或返回 ErrorAttributes 对象。
Spring Boot 将 /error 注册为 Servlet 容器的错误页面入口,并为 JSON 客户端生成错误响应,因此可以复用已有的 ErrorAttributes 和 BasicErrorController。Spring Boot 错误处理说明
为什么原来的参数无法注入
@ExceptionHandler 方法的参数由 Spring MVC 参数解析器提供,不会对任意参数执行 Bean 注入。它支持异常对象、WebRequest、HttpServletRequest、HttpServletResponse 等类型,但没有内置的 ErrorAttributes 参数解析器,因此会出现 No suitable resolver。[支持的方法参数](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-exceptionhandler.html# mvc-ann-exceptionhandler-args)
如果需要访问 ErrorAttributes Bean,应通过构造器注入。ErrorAttributes 是提取错误属性的接口,不能直接作为错误响应 DTO;用于响应的数据是 getErrorAttributes(...) 返回的 Map。ErrorAttributes API
修改异常处理方法
将原来的 handler 替换为下面的实现。InvalidTransferException 使用项目中已有的异常类:
import java.io.IOException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(InvalidTransferException.class)
public void handle(
InvalidTransferException ex,
HttpServletResponse response) throws IOException {
response.sendError(
HttpStatus.UNPROCESSABLE_CONTENT.value(),
ex.getMessage());
}
}
这个 handler 负责确定状态码和错误消息。Servlet 容器随后执行错误分派,由默认 /error 流程生成响应体。
调用 sendError 后直接结束方法,不再返回 ResponseEntity 或写入响应体。只调用 response.setStatus(422) 不足以触发同样的错误分派流程。
配置异常消息输出
在 Spring Boot 4 的 application.properties 中配置:
spring.web.error.include-message=always
Spring Boot 4 使用 spring.web.error.* 配置默认错误响应,其中 include-message 默认为 never。需要保留 message 字段时,应显式开启。Spring Boot 4 配置属性
默认的 DefaultErrorAttributes 会优先读取 Servlet 错误消息属性;该值为空时,再尝试读取异常消息。因此,传给 sendError 的 ex.getMessage() 可以进入最终响应的 message 字段。DefaultErrorAttributes 实现
客户端请求应接受 JSON,例如设置请求头:
Accept: application/json
当异常消息为 Cannot perform transfer to the same card 时,在默认配置及上述消息配置下,响应结构应类似:
{
"timestamp": "2026-05-15T15:55:24.553Z",
"status": 422,
"error": "Unprocessable Content",
"path": "/api/cards/transfer",
"message": "Cannot perform transfer to the same card"
}
这里沿用问题中的时间作为示意,实际时间由请求发生时的错误处理过程生成。字段顺序不应作为接口约定。
保持响应一致需要满足哪些条件
自定义异常和其他进入默认 /error 流程的异常会使用同一套错误属性生成机制。以下情况需要另外检查:
- 已有的其他
@ExceptionHandler如果直接返回自定义响应,仍然由它们决定各自的响应结构。 - 如果替换了
ErrorController或ErrorAttributes,最终字段取决于替换后的实现。 - 如果启用了 Problem Details,或通过
ResponseEntityExceptionHandler返回ProblemDetail,部分异常可能采用另一种结构。希望使用默认格式时,应检查这些配置。Spring Boot 4 的spring.mvc.problemdetails.enabled默认值为false。相关配置说明
spring.web.error.include-message=always 会影响所有经过默认错误处理流程的响应,因此业务异常的消息应适合直接展示。如果只需要公开指定业务异常的消息,可以集中定制 ErrorAttributes 的消息策略,同时复用其余默认属性。
验证时,应在实际启动的 Servlet 应用中触发该异常,检查 HTTP 状态、JSON 字段和消息内容。此方案依赖容器执行错误分派,单独调用 handler 方法无法验证完整响应链路。
备注:内容仅供参考。
