Explain Codes LogoExplain Codes Logo

How to specify the default error page in web.xml?

web-development
error-handling
best-practices
web-xml
Anton ShumikhinbyAnton Shumikhin·Jan 26, 2025
TLDR

To set a default error page in a Java EE web app, use <error-page> element in web.xml file. For server errors, use <error-code> 500 and for exceptions, use <exception-type> java.lang.Throwable:

<error-page> <error-code>500</error-code> // "Hello server error, my old friend" 😅 <location>/error.jsp</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type> // Catches like a pro baseball player! ⚾ <location>/error.jsp</location> </error-page>

Alter "/error.jsp" to align with the path of your chosen error page.

Error Pages for specific HTTP errors

It's useful to tailor error pages for specific HTTP status codes like 401 (Unauthorized), 403 (Forbidden), and 404 (Not Found):

<error-page> <error-code>404</error-code> // "Oops, the page pulled a Houdini" 😉 <location>/404.jsp</location> </error-page> <error-page> <error-code>403</error-code> // "Sorry, that's a secret area" 🕵️‍♀️ <location>/403.jsp</location> </error-page>

Exception Mapping in error pages

When it comes to handling Java exceptions, the <exception-type> element is your best friend:

<error-page> <exception-type>com.myapp.CustomException</exception-type> // Handled like a pro! 🩺 <location>/exception.jsp</location> </error-page>

Good practices for error handling

In terms of error handling, here are a few top tips:

  • Always ensure your error page is readily accessible.
  • Clarify errors using user-friendly language.
  • Monitor and learn from errors by logging them.
  • Uphold a design consistency between error pages and the rest of your website.

Enhance user experiences during errors

Meaningful error information

Personalize your error pages for optimal user assistance. Keep things simple and friendly — remember, no one likes a know-it-all!

Exception and HTTP statuses alignment

For skyrocketing user experiences, consider assigning unique pages to handle individual exception types. But remember! Only use an HTTP status error code when its description matches the situation.

Healthy habit of error logging

Don't forget to log the errors in the backend for further investigation and improvements. Log4j and SLF4J can come in handy to streamline the process!

Seamlessly blend in Error Pages

Wrath of the unforeseen

Sometimes, things go haywire — embrace it! Ensure a truly default error page for these unpredictable times:

<error-page> <location>/default-error.jsp</location> </error-page>

Consistency is key

Aim for consistency. Try to maintain seamless transitions to your error pages with common navigation and aesthetic elements in place!