<error-page> 在 web.xml 中定义总是返回 HTTP 状态 200

<error-page> defined in web.xml always comes back with HTTP status 200

我有一个在 Jboss 7 (EAP 6.4) 上运行的 EE6 JAX-RS 应用程序,它通过 ExceptionMapper.

的实现在内部处理大部分异常和错误

但是,在某些情况下(最明显的是当 HTTP Basic Auth 失败时)由于在调用应用程序之前发生错误而未调用它,因此客户端获得服务器的默认错误页面(JBWEB bla bla, HTML 带有难看的紫色。

现在为了捕获这些 "outer" 错误,我向 web.xml 添加了 <error-page> 定义,如下所示:

<error-page>
    <location>/error.json</location>
</error-page>
<error-page>
    <error-code>401</error-code>
    <location>/error401.json</location>
</error-page>

该位置工作正常,我几乎 得到了我想要的响应但是 HTTP 状态代码始终是 200。

至少可以说,这很烦人。如何将错误页面设为 return 正确的错误代码?

错误页面机制的目的是向最终用户展示人类可读的内容。如果 return 某些代码不是 200,它将由浏览器以通用方式处理(浏览器的标准错误消息)。

我最终得到的是编写一个小型网络服务(而不是静态页面),它将给我一个 JSON 响应和正确的 HTTP 状态代码,以及相关的 headers:

<error-page>
    <error-code>401</error-code>
    <location>/error/401</location>
</error-page>

哪个调用服务

@Path("/error")
public class ErrorService {

    private static final Map<Integer, String> statusMsg;
    static
    {
        statusMsg = new HashMap<Integer, String>();
        statusMsg.put(401, "Resource requires authentication");
        statusMsg.put(403, "Access denied");
        statusMsg.put(404, "Resource not found");
        statusMsg.put(500, "Internal server error");
    }

    @GET
    @Path("{httpStatus}")
    public Response error(@PathParam("httpStatus") Integer httpStatus) {

        String msg = statusMsg.get(httpStatus);
        if (msg == null)
            msg = "Unexpected error";

        throw new MyWebApplicationException.Builder()
            .status(httpStatus)
            .addError(msg)
            .build();
    }

}

我有一个异常 class MyWebApplicationException,它有自己的构建器模式,我之前已经使用 jax-rs 将各种应用程序错误格式化为 JSON ] ExceptionMapper.

所以现在我只是通过相同的渠道手动输入外部捕获的错误(比如 JAX-RS 之外发生的 401)。