如何把自定义 BookNotFoundException 映射为 404 并返回 JSON 错误体?

解读

在国内一线互联网或金融企业的 Struts 项目中,“异常转 HTTP 状态码 + 统一 JSON 错误体” 是 REST 化改造的高频考点。面试官想确认你能否:

  1. 让 Struts 的 声明式异常映射 与 HTTP 状态码 打通;
  2. 兼顾 内容协商(Content-Type=application/json);
  3. 不破坏 Struts 拦截器栈的执行顺序,保证事务、日志等切面仍生效;
  4. 在 生产环境 中可灰度、可扩展。

知识点

  • struts.xml 中 <global-exception-mappings> 与 <exception-mapping> 的语义差异
  • ExceptionMappingInterceptor 的 logEnabled、logLevel、logCategory 参数对线上排障的意义
  • StrutsConstants.STRUTS_HANDLE_EXCEPTION 开关与 struts.handle.exception 属性,决定异常是否由框架接管
  • @Result 的 type="httpheader" 与 type="json" 的组合技巧
  • com.opensymphony.xwork2.util.TextParseUtil 对 OGNL 占位符的解析顺序,防止 404 时仍进入 200 渲染
  • JSON 插件(struts2-json-plugin)的 root 对象 与 excludeProperties 在错误场景下的裁剪策略
  • Spring 托管的 ExceptionHandler 与 Struts 原生映射的优先级规则(先局部后全局,先注解后 XML)
  • Servlet 容器(如 Undertow/Tomcat)对 4xx 错误页的默认转发行为,避免被容器吞掉响应体

答案

步骤一:定义统一错误体

public class JsonError {
    private int status;
    private String code;
    private String message;
    private String path;
    // getter/setter 省略
}

步骤二:自定义异常

public class BookNotFoundException extends RuntimeException {
    public BookNotFoundException(String isbn) {
        super("图书不存在: " + isbn);
    }
}

步骤三:在 struts.xml 中声明全局异常映射

<package name="rest" namespace="/api" extends="json-default">
    <global-exception-mappings>
        <exception-mapping exception="com.xxx.BookNotFoundException" result="book404"/>
    </global-exception-mappings>

    <global-results>
        <result name="book404" type="json">
            <param name="statusCode">404</param>
            <param name="root">error</param>
            <param name="excludeNullProperties">true</param>
        </result>
    </global-results>
</package>

步骤四:提供 专用的 ExceptionAction 作为错误工厂,由 Struts 自动注入异常实例

@Action(value = "exception")
public class ExceptionAction extends ActionSupport {
    private JsonError error;
    private HttpServletRequest request;

    @Override
    public String execute() {
        Object ex = request.getAttribute("exception");
        if (ex instanceof BookNotFoundException) {
            error = new JsonError(404, "BOOK_NOT_FOUND", ex.toString(), request.getRequestURI());
        }
        return "book404";
    }

    public JsonError getError() { return error; }
}

步骤五:在 web.xml 关闭容器默认 404 转发,确保 Struts 完全接管

<error-page>
    <error-code>404</error-code>
    <location>/api/exception</location>
</error-page>

步骤六:验证

  1. 请求 GET /api/book/999 抛出 BookNotFoundException;
  2. 响应头 HTTP/1.1 404;
  3. 响应体
{"status":404,"code":"BOOK_NOT_FOUND","message":"图书不存在: 999","path":"/api/book/999"}

满足 RFC 7807 Problem Details 风格,可直接供前端统一弹窗。

拓展思考

  • 若项目已接入 SpringMVC 注解驱动,可用 @ControllerAdvice + @ExceptionHandler 替代 Struts 映射,但需关闭 struts.objectFactory.spring.autoWire.alwaysRespect,防止双重代理;
  • 对 敏感异常信息(如 SQL 语句)需二次脱敏,可扩展 ExceptionMappingInterceptor 的 publishException 方法,加入 正则黑名单;
  • 在 金融级系统 中,404 错误体需携带 traceId,可借助 MDC 把 UUID 写入 JsonError,方便 ELK 链路追踪;
  • 若未来迁移到 Struts 6,官方已标记 FilterDispatcher 彻底删除,需改用 StrutsPrepareAndExecuteFilter 并开启 <constant name="struts.handle.exception" value="true"/>,否则全局异常映射失效;
  • 压测场景 下,建议把异常 Action 的 json 结果 加上 GZIP 压缩 与 Cache-Control: no-cache,避免 404 被 CDN 缓存导致误报警。