I’m having a tough time consolidating errors in my application. Currently, my error.jsp looks like following (part of it):
<%@ page isErrorPage="true" %>
<%@page contentType="text/html"%>
<%@page import="java.util.*"%>
<%@page import="javax.servlet.*"%>
<%@page import="javax.servlet.http.*"%>
<%@page import="java.util.Calendar"%>
<%@page import="java.text.SimpleDateFormat"%>
<html>
<%
String code = null, message = null, type = null, uri = null, time = null;
Object codeObj=null, messageObj=null, typeObj=null;
if (request.getAttribute("javax.servlet.error.status_code") != null)
codeObj = request.getAttribute("javax.servlet.error.status_code");
if (request.getAttribute("javax.servlet.error.message") != null)
messageObj = request.getAttribute("javax.servlet.error.message");
if (request.getAttribute("javax.servlet.error.exception_type")!=null)
typeObj = request.getAttribute("javax.servlet.error.exception_type");
if (codeObj != null) code = codeObj.toString();
if (messageObj != null) message = messageObj.toString();
if (typeObj != null) type = typeObj.toString();
uri = (String) request.getAttribute("javax.servlet.error.request_uri");
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
time = sdf.format(cal.getTime());
String error = "Code:\t\t" + code + "\nType:\t\t" + type + "\nURL:\t\t" + uri + "\nTime:\t\t" + time +"\nMessage:\t" + message;
%>
This works fine in all scenarios except!:
Sometimes in my application I am catching built-in exceptions in MyException class with the following code:
catch(MyException ex){
log.error(ex.getMessage(), uivex);
String originalURL = "/errorpages/error.jsp?errorcode=" + (ex.getMajor() + ex.getMinor()) + "&errormessage=" + ex.getMessage();
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address);
dispatcher.forward(request,response);
}
Now the problem is that when I get forwarded to error.jsp page…Instead of seeing the actual error from MyException class..I’m seeing NullPointerException because nothing is present in javax.servlet.error.status_code and the page is declared as isErrorPage="true"
What should I do in this case? One solution is to make a completely different error.jsp (name it error1.jsp) page and forward the exceptions from MyException class to that page. Though, I would like to have everything in one place.
This code honestly hurts my eyes. Here is how a generic one should look like. You may find it useful.
The
@page isErrorPageis by the way only useful if you want to have the${exception}(i.e.request.getAttribute("exception")available in the JSP. In this particular case you don’t need it.And indeed, do not forward in the
catchblock at all. Just let it go. It will be dealt by the error page then.