Monday, May 14, 2007

HTTP Status Code & Error Handling

1xx Informational
2xx Successful (200 OK)
3xx Redirection (302 Found)
4xx Client Error (403 Forbidden 404 Not Found)
5xx Internal Server Error

We can define how a web application handles errors using the error-page element in the WEB-INF/web.xml file. The error-page element defines exceptions by exception type or by error code, as the following sections describe. The order of these elements in the web.xml file determines the error handler.


<error-page>
<error-code>500</error-code>
<location>/common/error/handleGeneralError.jsp</location>
</error-page>

<error-page>
<exception-type>java.io.FileNotFoundException </exception-type>
<location>/error-pages/404.jsp </location>
</error-page>

The HttpServletRequest and HttpServletResponse objects provide access to error information
...

Object status_code = req.getAttribute("javax.servlet.error.status_code");
Object message = req.getAttribute("javax.servlet.error.message");
Object error_type = req.getAttribute("javax.servlet.error.exception_type");
Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
Object request_uri = req.getAttribute("javax.servlet.error.request_uri");

With such error information, we can delegate the error handling to one Action class which provides fine grained control, e.g, printStackTrace on screen on dev mode.

No comments: