Java Reference
In-Depth Information
We can extend
DefaultExceptionHandler
and add a method that handles
Throwable
, using a
ForwardResolution
to display the exception page:
package
stripesbook.ext;
public class
MyExceptionHandler
extends
DefaultExceptionHandler {
private static final
String VIEW = "/WEB-INF/jsp/exception.jsp";
private static final
Log log =
Log.getInstance(MyExceptionHandler.
class
);
public
Resolution catchAll(Throwable exc, HttpServletRequest req,
HttpServletResponse resp)
{
log.error(exc);
return new
ForwardResolution(VIEW);
}
}
The name of the method can be whatever we want. What's important is
that the method be
public
and accept the three parameters. Returning
a
Resolution
is optional.
Now, we can easily add handler methods for specific exceptions. For
example, the exception thrown when trying the
/Admin.action
URL is
actually an
ActionBeanNotFoundException
. In that case, we can use
Error-
Resolution
to return an HTTP error code back to the client: the infamous
404.
HttpServletResponse
contains constants for error codes, so we'll use
that:
public
Resolution catchActionBeanNotFound(
ActionBeanNotFoundException exc,
HttpServletRequest req, HttpServletResponse resp)
{
return new
ErrorResolution(HttpServletResponse.SC_NOT_FOUND);
}
Next, we'll configure the application to use
not_found.jsp
for the 404 error
code:
<error-page>
<error-code>
404
</error-code>
<location>
/WEB-INF/jsp/not_found.jsp
</location>
</error-page>
Search WWH ::
Custom Search