Java – JSP: How can I keep the code running even if I can’t display the error page?

JSP: How can I keep the code running even if I can’t display the error page?… here is a solution to the problem.

JSP: How can I keep the code running even if I can’t display the error page?

I defined an error page in my web.xml:

 <error-page>
   <exception-type>java.lang.Exception</exception-type>
   <location>/error.jsp</location>
 </error-page>

In that error page, I created a custom label. The tag handler for this tag emails me stack trace information about any errors that occur. In most cases, this works well.

If the output has already started to be sent to the client when the error occurs, it will not work well. In that case, we get this:

SEVERE: Exception Processing ErrorPage[exceptionType=java.lang.Exception, location=/error.jsp]
 java.lang.IllegalStateException

I think this error occurs because we can’t redirect the request to the error page after the output has already started. The workaround I used was to increase the buffer size on particularly large JSP pages. But I’m trying to write a generic error handler that can be applied to existing applications, but I’m not sure if it’s feasible to iterate through hundreds of JSP pages to make sure their buffers are large enough.

Is there a way to still allow my stack trace email code execution in this case, even though I can’t actually show the error page to the client?

Solution

If you have already started sending data to the client, you will not use errorPage.
What I did was use JavaScript callbacks to check for incomplete pages and then redirect to the error page. At the beginning of the page that contains headers or something else, initialize the Boolean JavaScript variable to false and register an onload handler to check the status and redirect to the error page.

<script type="text/javascript">
        var pageLoadSuccessful = false;//set to true in footer.jsp
        dojo.addOnLoad(function(){
            if (!pageLoadSuccessful) window.location = "<c:url value="/error.do" />";
        });
</script>

Then in the footer JSP, make sure this variable is set to true:

<script type="text/javascript">
    pageLoadSuccessful = true;//declared in header.jsp
</script>

Related Problems and Solutions