如何自定义 ProblemDetail 扩展字段?

解读

在 Spring Framework 6 / Spring Boot 3 之后,RFC 7807 的 application/problem+json 成为默认的异常响应格式。
面试官问“如何自定义扩展字段”,考察的是:

  1. 你是否知道 ProblemDetail 是 不可变 DTO,官方只预留了 properties 字段做扩展;
  2. 你是否能在 不破坏 REST 风格 的前提下,把业务码、用户提示、追踪 ID 等国产系统中必现的字段塞进去;
  3. 你是否熟悉 Spring 6 提供的增强钩子(ResponseEntityExceptionHandler 的 handleExceptionInternal 与 ErrorResponse 接口),而不是再去写传统的 @ControllerAdvice + @ExceptionHandler 返回自定义 VO。
    一句话:既要 合规(遵循 RFC 7807),又要 接地气(满足国内前端需要)。

知识点

  • ProblemDetail 结构:type、title、status、detail、instance 五个标准字段,额外字段必须放在 Map<String,Object> properties 里;
  • Spring 6 新增接口:ErrorResponse 封装 ProblemDetail,允许一次性携带 HTTP 状态与扩展数据;
  • 核心扩展点:
    1. 直接 problemDetail.setProperty(key,value);
    2. 实现 ErrorResponse 的 getBody() 返回已填充的 ProblemDetail;
    3. 在 @ControllerAdvice 中覆盖 ResponseEntityExceptionHandler.handleExceptionInternal(...),对父类已经构造好的 ProblemDetail 二次加工;
  • 线程安全:ProblemDetail 本身无状态,但 properties 是 LinkedHashMap,多线程场景下需防御性复制或只读暴露;
  • 国产规范兼容:国内多数企业要求返回 { "code": 10001, "msg": "用户不存在", "traceId": "0a1b2c3f...", "data": null },可通过扩展字段兼容,无需再造新媒体类型;
  • Spring Boot 自动配置:ErrorMvcAutoConfiguration 只识别 ErrorResponse 与 ProblemDetail,若你返回自定义 VO,Content-Negotiation 会回退到 text/html,导致生产环境出现 Whitelabel 页面,属于重大事故。

答案

步骤一:定义业务异常,实现 ErrorResponse

public class BizException extends RuntimeException implements ErrorResponse {
    private final int bizCode;
    private final String traceId;

    public BizException(int bizCode, String message, String traceId) {
        super(message);
        this.bizCode = bizCode;
        this.traceId = traceId;
    }

    @Override
    public ProblemDetail getBody() {
        ProblemDetail detail = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
        detail.setTitle("业务校验失败");
        detail.setDetail(getMessage());
        // 扩展字段
        detail.setProperty("code", bizCode);
        detail.setProperty("traceId", traceId);
        detail.setProperty("timestamp", Instant.now().toEpochMilli());
        return detail;
    }

    @Override
    public HttpStatusCode getStatusCode() {
        return HttpStatus.BAD_REQUEST;
    }
}

步骤二:全局兜底,给框架默认异常也加上扩展字段

@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleExceptionInternal(
            Exception ex, Object body, HttpHeaders headers,
            HttpStatusCode status, WebRequest request) {

        // 1. 让父类先构造标准 ProblemDetail
        ResponseEntity<Object> entity = super.handleExceptionInternal(ex, body, headers, status, request);

        // 2. 二次加工:补充 traceId 与统一 code
        if (entity.getBody() instanceof ProblemDetail pd) {
            pd.setProperty("code", 9999);          // 统一系统异常码
            pd.setProperty("traceId", MDC.get("traceId"));
        }
        return entity;
    }
}

步骤三:验证响应

HTTP/1.1 400
Content-Type: application/problem+json

{
  "type": "about:blank",
  "title": "业务校验失败",
  "status": 400,
  "detail": "用户状态异常",
  "code": 10001,
  "traceId": "0a1b2c3f9e",
  "timestamp": 1718888888888
}

关键点:

  • 绝不自己 new 一个 VO 返回,始终复用 ProblemDetail;
  • 扩展字段名避开官方保留字(type、title、status、detail、instance),防止未来升级冲突;
  • 若使用 WebFlux,实现 ErrorResponseException 即可,API 与 MVC 保持对称。

拓展思考

  1. 多语言提示:在 properties 里再放一个 i18nKey,由前端根据 Accept-Language 自行映射,避免后端拼接中文导致缓存失效;
  2. 分页异常:返回 ProblemDetail 时把当前页、最大页放入扩展字段,让前端弹 toast 的同时可直接跳转最后一页;
  3. 敏感字段脱敏:traceId 在网关层已经透传,禁止把用户 ID、手机号直接塞进 properties,可映射为 userIdHash;
  4. OpenAPI 文档:使用 springdoc-openapi 时,通过 OpenApiCustomizer 把扩展字段写入 schema.example,保证前端生成的 TS 类型带 code/traceId,减少联调成本;
  5. 向下兼容:老项目原来返回 { "success":false,"errorCode":xxx },可在 ProblemDetail 里加一个 legacy 节点,双写字段平滑迁移,避免 APP 强更。