Skip to content

Instantly share code, notes, and snippets.

@yyunikov
Last active Aug 29, 2015
Embed
What would you like to do?
Example of error handling for Java web applications
<servlet>
<servlet-name>NotFoundErrorHandler</servlet-name>
<servlet-class>NotFoundErrorHandler</servlet-class>
</servlet>
<servlet>
<servlet-name>ErrorHandler</servlet-name>
<servlet-class>ErrorHandler</servlet-class>
</servlet>
<!-- servlet mappings -->
<servlet-mapping>
<servlet-name>NotFoundErrorHandler</servlet-name>
<url-pattern>/notfound</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ErrorHandler</servlet-name>
<url-pattern>/error</url-pattern>
</servlet-mapping>
<!-- error pages -->
<error-page>
<error-code>500</error-code>
<location>/error</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/notfound</location>
</error-page>
@WebServlet("/error")
public class ErrorHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processError(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processError(request, response);
}
private void processError(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// do something with your error and show the error page
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment