Wiki

Clone wiki

demo / Error

Error Pages

There are two ways to serve out error pages in our application. Spring can map exceptions to error pages and our servlet can map http error codes and exceptions to error pages as well.

Servlet Error Pages

We'll be mapping 400 and 404 error codes to a simple custom page in our web.xml. These pages will NOT be processed by any filters before being served out. See

WEB-INF/jsp/errors/404.jsp
WEB-INF/jsp/errors/400.jsp

these pages just print out some static text.

In web.xml we add the following

<error-page>
	<error-code>404</error-code>
	<location>/WEB-INF/jsp/error/404.jsp</location>
</error-page>

<error-page>
	<error-code>400</error-code>
	<location>/WEB-INF/jsp/error/400.jsp</location>
</error-page>

where error-code is our http error code and location is the path to our jsp.

Note

error-page can also take an exception-type element, but we will be using Spring to map our exceptions.

Spring Error Pages

While we were using the servlet to map http status codes, we will be using spring to map our exceptions to error pages. This way our exception pages will be processed by our filters unlike when mapping through web.xml. See

WEB-INF/jsp/errors/default-error.jsp

which we will map to all Exception in our MvcConfig.java file.

@Bean
public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
	SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
	resolver.setDefaultErrorView("error/default-error");
	resolver.setDefaultStatusCode(500);
	return resolver;
}

Here we have a special bean that spring will automatically register. Here I'm just using the defaultErrorView to map any exception type to our page but you can map as many exceptions to views as necessary. By default you can access the exception via exception variable. Take a look at default-error.jsp for example

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>An Error has Occured.</title>
</head>
<body>
	This error page was served by Spring.
	<div>${exception}</div>
</body>
</html>

We have /demo/users/error mapped to throw an exception to demonstrate.

Updated