当验证失败时,如何让 REST 插件返回 422 而非 400?

解读

在国内企业级 Java 面试中,**“REST 插件返回码定制”**是高频考点。
Struts2 的 struts2-rest-plugin 默认把验证失败映射到 400 Bad Request,而阿里、美团等一线团队在做前后端分离时,普遍要求 422 Unprocessable Entity 以区分“语法错误”与“语义错误”。
面试官真正想听的是:

  1. 你是否知道 rest-plugin 的 CodeBehind 机制;
  2. 能否在不改源码的前提下,用 Struts 的声明式异常映射 + 自定义 Result 优雅解决;
  3. 是否了解 422 与 400 的语义差异并能自圆其说。

知识点

  1. rest-plugin 默认异常处理链
    ValidationInterceptor → WorkflowInterceptor → DefaultActionInvocation → CodeBehindInterceptor → RestActionInvocation → 400 Result。
  2. 关键常量
    rest-plugin 内部硬编码了 ServletActionContext.getResponse().sendError(400),位于 org.apache.struts2.rest.RestActionInvocation 的 handleValidationFailure()。
  3. Struts 异常映射优先级
    当 exceptionMappings 存在时,会覆盖 interceptor 的默认行为,这是破解入口。
  4. 422 语义
    RFC 4918 定义 422 表示“语法正确但语义错误”,国内大厂普遍用它承载字段级校验失败,方便前端弹层提示。
  5. 零侵入方案
    利用 @ExceptionMapping + 自定义 Result + 自定义 StatusHolder 即可,无需改 jar。

答案

步骤一:自定义一个“校验失败”异常

public class Validation422Exception extends RuntimeException {
    private final Map<String,String> fieldErrors;
    public Validation422Exception(ActionSupport action) {
        this.fieldErrors = action.getFieldErrors()
                                .entrySet()
                                .stream()
                                .collect(Collectors.toMap(
                                    Map.Entry::getKey,
                                    e -> e.getValue().get(0)));
    }
    public Map<String,String> getFieldErrors(){ return fieldErrors; }
}

步骤二:在 Action 基类里把验证失败转成异常

@Override
public void validate() {
    if (hasFieldErrors()) {
        throw new Validation422Exception(this);
    }
}

步骤三:在 struts.xml 中做异常映射

<package name="rest" namespace="/api" extends="rest-default">
    <global-exception-mappings>
        <exception-mapping exception="com.xxx.Validation422Exception" result="422"/>
    </global-exception-mappings>
    <global-results>
        <result name="422" type="json">
            <param name="statusCode">422</param>
            <param name="excludeNullProperties">true</param>
        </result>
    </global-results>
</package>

步骤四:让 422 Result 输出统一格式

public class Json422Result extends JSONResult {
    @Override
    protected void doExecute(String location, ActionInvocation ai) throws Exception {
        HttpServletResponse res = ServletActionContext.getResponse();
        res.setStatus(422);
        Validation422Exception ex = (Validation422Exception) ai.getResultCode().equals("422")
                                    ? ai.getInvocationContext().getValueStack().findValue("exception")
                                    : null;
        Map<String,Object> body = new HashMap<>();
        body.put("code", 422);
        body.put("message", "字段校验失败");
        body.put("errors", ex == null ? Collections.emptyMap() : ex.getFieldErrors());
        writeResponse(body, res);
    }
    private void writeResponse(Map<String,Object> body, HttpServletResponse res) throws IOException {
        res.setContentType("application/json;charset=UTF-8");
        new ObjectMapper().writeValue(res.getWriter(), body);
    }
}

注册自定义结果类型:

<result-types>
    <result-type name="json422" class="com.xxx.Json422Result"/>
</result-types>

并把全局 result 的 type 改为 json422 即可。

效果:当字段校验失败时,前端收到的 HTTP 状态码为 422,响应体为

{"code":422,"message":"字段校验失败","errors":{"userName":"用户名已存在"}}

拓展思考

  1. 与 SpringMVC 差异
    SpringMVC 用 @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY) 即可,而 Struts 必须走 异常映射链,这是框架设计哲学不同。
  2. 国际化提示
    在 Json422Result 里可注入 ActionSupport.getText(),把错误消息转中文,满足国内监管对提示语母语化的要求。
  3. 性能陷阱
    高并发场景下,每次 new Json422Result 会重复创建 ObjectMapper,建议用 ThreadLocal 或全局单例。
  4. 安全加固
    返回 422 时务必 过滤掉堆栈信息,否则可被攻击者利用做信息收集;Struts 的 devMode=false 只是第一步,仍需白名单序列化。
  5. 未来演进
    Struts 6 已标记 rest-plugin 为 deprecated,国内新项目若考虑 Jakarta EE 9+,应评估迁移到 Spring Boot + validation starter 的方案,但历史系统通过上述改造仍可安全服役。