How to show user-friendly error page in browser when runtime exception is thrown by servlet?
Asked Answered
S

3

39

I'm developing web-application with JSF. I tested it as I was able to but from time to time runtime exceptions are thrown.

So, how to redirect user to special error page every time an exception is thrown (instead of displaying 500 Error with full tomcat logs)?

Shandishandie answered 30/4, 2010 at 23:29 Comment(0)
A
59

Just declare an <error-page> in web.xml wherein you can specify the page which should be displayed on a certain Throwable (or any of its subclasses) or a HTTP status code. E.g.

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

which will display the error page on any subclass of the java.lang.Exception, but thus not java.lang.Throwable or java.lang.Error. This way you can have your own error page for any kind of Throwable. E.g. java.sql.SQLException, java.io.IOException and so on.

Or,

<error-page>
    <error-code>500</error-code>
    <location>/error.jsp</location>
</error-page>

which will display the error page on a HTTP 500 error, but you can also specify another ones for 404 (Page Not Found), 403 (Forbidden), etcetera.

If you declare <%@page isErrorPage="true" %> in top of error.jsp, then you have access to the thrown Exception (and thus also all of its getters) by ${exception} in EL.

<p>Message: ${exception.message}</p>

Also see the Java EE 5 tutorial on the subject.

Ayo answered 30/4, 2010 at 23:40 Comment(2)
What if I have a servlet rather than a jsp? Is there an equivalent for isErrorPage="true" ?Copulative
The equivalent for non-JSP is request.getAttribute(RequestDispatcher.ERROR_EXCEPTION).Guthrie
B
10

In your web.xml:

<error-page>
  <error-code>500</error-code>
  <location>/errorpages/500.jsp</location>
</error-page>

You may also catch specific exceptions or exceptions which extend Throwable:

<error-page>
  <exception-type>java.lang.Throwable</exception-type>
  <location>/errorpages/500.jsp</location>
</error-page>
Bacteroid answered 30/4, 2010 at 23:39 Comment(0)
P
0
    If you use java config in spring, you can follow,

   @Configuration
   public class ExcpConfig {

    @Bean(name = "simpleMappingExceptionResolver")
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver resolver= new SimpleMappingExceptionResolver();

        Properties mappings = new Properties();
        resolver.setExceptionMappings(mappings); // None by default
        resolver.setExceptionAttribute("ErrorOccurred"); // Default is "exception"
        resolver.setDefaultErrorView("500"); // 500.jsp
        return r;
    }

}
Paucker answered 1/12, 2014 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.