In this article, I will help you understand the default error handling in Spring Boot, how to use custom error pages (for common HTTP error codes like 403, 404, 500…) and how to code a custom error controller in order to perform additional code when an error occurred, e.g. logging more information about the error.

 

1. Default Whitelabel Error Page

By default, Spring Boot will display the Whitelabel error page when an error occurred. For example, when a page could not be found (HTTP 404 error):

spring boot whitelable error 404

Or when an exception is thrown by Java Virtual Machine, causing HTTP 500 Internal server error – the white label error page gets displayed with the exception stack trace:

spring boot whitelable error 500

This kind of error page is certainly not friendly to the end users, and Spring Boot prints this statement:

This application has no explicit mapping for /error, so you are seeing this as a fallback.

That means programmers should handle mapping for /error URL and provide custom, user-friendly error pages.

Spring Boot allows programmers to disable the white label error page by setting the following property in the application.properties file:

server.error.whitelabel.enabled=false

Then the raw error page provided by the server gets displayed, i.e. Tomcat like this:

tomcat internal server error

Anyway, we should provide custom error pages instead of the default ones which are very technical to the end users.

 

2. Use Custom Error Pages

Spring Boot makes it easy to override the default whitelabel error page. Just create the error.html page under the src/main/resources/templates directory. For example, with the following code:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Error</title>
</head>
<body>
	<h3>Sorry, there was an error occurred!</h3>
</body>
</html>

Then when any error occurred, this custom error page will get displayed:

general custom error page

You can also provide custom error page for a specific HTTP status code (403, 404, 500, etc) – just by creating the 403.html (Forbidden error), 404.html (Page not found error), 500.html (Internal server error)… files under the templates/error directory (you must create error directory):

custome error pages in spring boot project

That’s it – very simple! Thanks to Spring Boot’s default configurations do all the details behind the scene.

 

3. Implement Custom Error Controller

In case you want to perform some tasks before the custom error pages get displayed, you can code a controller class implementing the ErrorController interface like this:

package net.codejava;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class CustomErrorController  implements ErrorController {

	@GetMapping("/error")
	public String handleError(HttpServletRequest request) {
		String errorPage = "error";	// default
		
		Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
		
		if (status != null) {
			Integer statusCode = Integer.valueOf(status.toString());
			
			if (statusCode == HttpStatus.NOT_FOUND.value()) {
				// handle HTTP 404 Not Found error
				errorPage = "error/404";
				
			} else if (statusCode == HttpStatus.FORBIDDEN.value()) {
				// handle HTTP 403 Forbidden error
				errorPage = "error/403";
				
			} else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
				// handle HTTP 500 Internal Server error
				errorPage = "error/500";
				
			}
		}
		
		return errorPage;
	}
	
	@Override
	public String getErrorPath() {
		return "/error";
	}
}

Here, the getErrorPath() method returns a URL to which will be forwarded when an error occurs. And this error path is handled by the handler method right in this class. I showed you the code that returns the corresponding error page name based on HTTP status code, and you can add code to perform the logics you want to execute before the error pages get displayed.

Note that all exceptions are logged by Spring Boot by default, so you don’t have to log the errors again here in this custom controller class.

In case you want to handle specific exception classes rather than HTTP error code, follow this article: Spring Boot Controller-Based Exception Handler Examples

 

Conclusion

So far you have learned how to provide custom error pages in a Spring Boot application, and how to intercept the requests before those error pages get displayed. Again, Spring Boot makes error handling simple, easy and convenient. For reference, you can download the sample Spring Boot project attached below, and watch the following video to see the code in action:

 

Related Tutorials:

 

Other Spring Boot Tutorials:

 


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (SpringBootErrorHandling.zip)SpringBootErrorHandling.zip[Sample Spring Boot project]75 kB

Add comment