page> defined in web.xml always comes back with HTTP status 200
I have an EE6 JAX-RS application that runs on Jboss 7 (EAP 6.4) and handles most of its exceptions and errors internally through an implementation of ExceptionMapper
.
There are circumstances, though, (most notably when HTTP Basic Auth fails) when this is not invoked because the error occurs before the application is invoked, and thus the client gets the server's default error page (JBWEB bla bla, HTML with ugly purple colors).
Now in order to catch these "outer" errors I added <error-page>
definitions to web.xml
like so:
<error-page>
<location>/error.json</location>
</error-page>
<error-page>
<error-code>401</error-code>
<location>/error401.json</location>
</error-page>
The location works fine and I almost get the response I want but the HTTP status code is always 200.
That is annoying, to say the least. How do I get the error page to return its proper error code?
What I ended up with was writing a small web service (instead of a static page) that would give me a JSON response and the correct HTTP status code, plus relevant headers:
<error-page>
<error-code>401</error-code>
<location>/error/401</location>
</error-page>
Which calls the service
@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();
}
}
I have an exception class MyWebApplicationException
with its own builder pattern that I've already previously used to format all sorts of application errors as JSON using a jax-rs ExceptionMapper
.
So now I'm just manualle feeding externally caught errors (like the 401 that happens outside of JAX-RS) through the same channel as well.
The intention of error-page mechanism is to show end user something human readable. In case it return some code other than 200 it would be processed by browser in common way (browser's standard error message).
链接地址: http://www.djcxy.com/p/45586.html上一篇: 如何获得状态码?