Andy Jarrett // Code. Develop. Create.

Catching all exceptions and errors in a J2EE app

A lot of the text I have come across that deals with catching errors using the web.xml focuses on specific errors only. Below is some code for catching all generic errors thrown by a servlet.

First; Put the following in your web.xml

java.lang.Throwable /generic_errors.jsp

Second; Create a file called /generic_errors.jsp in your web root and add the following.

<%@ page contentType="text/html"%><%@ page language="java"%><%@ page isErrorPage="true" import="java.io.*" %>Something hasn't gone to plan!

Something hasn't gone to plan!

An errror has occured. Please use the back button or contact support.

<%if( request.getRemoteAddr().equals("127.0.0.1") ){ out.print("The following error has occured: "+ exception.toString() +"

"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); out.print(sw); sw.close(); pw.close();}%>

I’m here, learning and working away. If you liked this content and want to keep me going, consider buying me a coffee. Your support keeps this site running and the coffee brewing! ☕️