如何自定义 ProblemDetail 扩展字段?
解读
在 Spring Framework 6 / Spring Boot 3 之后,RFC 7807 的 application/problem+json 成为默认的异常响应格式。
面试官问“如何自定义扩展字段”,考察的是:
- 你是否知道
ProblemDetail是 不可变 DTO,官方只预留了properties字段做扩展; - 你是否能在 不破坏 REST 风格 的前提下,把业务码、用户提示、追踪 ID 等国产系统中必现的字段塞进去;
- 你是否熟悉 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 状态与扩展数据; - 核心扩展点:
- 直接
problemDetail.setProperty(key,value); - 实现
ErrorResponse的getBody()返回已填充的ProblemDetail; - 在
@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 保持对称。
拓展思考
- 多语言提示:在
properties里再放一个i18nKey,由前端根据Accept-Language自行映射,避免后端拼接中文导致缓存失效; - 分页异常:返回
ProblemDetail时把当前页、最大页放入扩展字段,让前端弹 toast 的同时可直接跳转最后一页; - 敏感字段脱敏:
traceId在网关层已经透传,禁止把用户 ID、手机号直接塞进 properties,可映射为userIdHash; - OpenAPI 文档:使用
springdoc-openapi时,通过OpenApiCustomizer把扩展字段写入schema.example,保证前端生成的 TS 类型带 code/traceId,减少联调成本; - 向下兼容:老项目原来返回
{ "success":false,"errorCode":xxx },可在ProblemDetail里加一个legacy节点,双写字段平滑迁移,避免 APP 强更。