Search code examples
javaservletsexceptionrequestdispatcher

Does javax.servlet.error.exception attribute always cast to java.lang.Exception type?


The attribute javax.servlet.error.exception in request with dispatcher type is ERROR can always cast to java.lang.Exception type?

I take a look at the javadoc, but it doesn't mention the type must be java.lang.Exception OR java.lang.Throwable.

I am asking this question because I am handling error page. If the attribute javax.servlet.error.exception always hold Exception type so I can write code as below without worrying about ClassCastException for all cases.

Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");

Of course I can do like this:

Throwable error = (Throwable)request.getAttribute("javax.servlet.error.exception");

but my handling is on Exception type ( Not Throwable ).

Thanks!


Solution

  • That depends on the <exception-type> associated with <error-page> entry in web.xml whose <location> refers the JSP/Servlet based resource in question.

    If there's none, i.e. you're using a general error page without any <exception-type>, or you're using only <error-code>500</error-code>, or you don't have any <error-page> at all, then assume java.lang.Throwable.

    If there's an explicit <exception-type>, then assume exactly that type registered in web.xml.

    Differently put, if you want to assume only java.lang.Exception, then set <exception-type> accordingly to that type.

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

    Beware though that this way any java.lang.Error (i.e. matching java.lang.Throwable) will slip through and end up in server's default error page when you don't have an <error-page> for 500 or java.lang.Throwable.

    See also: