Search code examples
javaexceptionjakarta-eeannotations

Handling exceptions in JavaEE without web.xml


Is there a way to map exception handling to a servlet or JSP without adding options into web.xml? How I understand starting from Java Servlets 3.0 all should be possible without web.xml.

I'm about this kind of options

<error-page>
  <exception-type>java.lang.RuntimeException</exception-type>
  <location>/WEB-INF/jsps/exception.jsp</location>
</error-page>

Solution

  • No, the current API requires you to put error-page in your web.xml for custom error handling. Servlet 3.0 is a step in the right direction, but it is not a fully-fledged replacement and you can't do everything you'd like to with annotations alone. Error pages are one of it's limitations.

    The most modern & minimal approach is to define a servlet resposible for handling your errors. See below.

    web.xml

    <error-page> 
        <exception-type>java.lang.RuntimeException</exception-type> 
        <location>/runtimeErrorHandler</location> 
    </error-page>
    

    RuntimeErrorHandlerServlet.java

    @WebServlet(urlPatterns = "/runtimeErrorHandler")
    public class RuntimeErrorHandlerServlet extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            resp.setContentType("text/html; charset=utf-8");
            try (PrintWriter writer = resp.getWriter()) {
                // Write your error handling page here...
            }
        }
    
    }
    

    Note that you should not be catching such broad exception types. Instead, you should handle the specific types you are concerned with.