Reputation: 65
I have the following lines in my web.xml that replace the stack trace rendering with a custom user-friendly error page.
<error-page>
<location>/error.html</location>
</error-page>
What I am wondering is if it is possible to have Tomcat log any exceptions handled by the error-page element to a log file. If I used access logs, I would see 500s but I wouldn't be able to see the stack trace. How can I get the stack trace into a log?
Upvotes: 3
Views: 1221
Reputation: 23054
You could create a dedicated servlet for handling errors.
<servlet>
<servlet-name>ErrorHandler</servlet-name>
<servlet-class>ErrorHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ErrorHandler</servlet-name>
<url-pattern>/ErrorHandler</url-pattern>
</servlet-mapping>
Then reference this in the <location>
of the <error-page>
:
<error-page>
<location>/ErrorHandler</location>
</error-page>
And then implement the ErrorHandler
servlet so that it logs the original exception before forwarding to the existing user friendly error page. For example:
public class ErrorHandler extends HttpServlet {
private static final Log LOG = LogFactory.getLog(ErrorHandler.class);
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
// Obtain the original exception
final Throwable throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
// Log the exception
log.error("Caught unhandled exception: " + e, e);
// Forward to the friendly error page
RequestDispatcher rd = req.getRequestDispatcher("error.html");
rd.forward(request, response);
...
}
}
Upvotes: 3