This post will discuss how to override the Spring Boot error page with our custom HTML page.

By default, Spring Boot displays a Whitelabel error page if we encounter a server error. To specify the custom error logic, we need a @Controller that handles the /error path or a View that resolves with a name of error. Let’s discuss both approaches in detail:

1. Implementing ErrorController interface

We know that Spring Boot automatically registers the BasicErrorController as a Spring Bean when the implementation of ErrorController is not provided. To replace the default behavior completely, implement the ErrorController interface, and override its getErrorPath() method to return the path of the error page, as shown in the following example.

2. Custom Error Pages

We can also display a custom HTML page for an error.

1. Let’s start by adding Thymeleaf template engine dependency to pom.xml.

 
2. Next, create a custom HTML error page, and label it as error.html.

 
3. Place error.html file under resources/templates directory. The folder structure would be as follows:

src/
 +- main/
    +- java/
    |   + <source code>
    +- resources/
        +- templates/
            +- error.html

 
4. Finally, add a bean that implements the ErrorViewResolver interface, as shown in the following example:

 
We can also display specific error pages for different error types. We can do this by naming the HTML file with the corresponding HTTP status code.

In the following example, different error pages are displayed for different HTTP status codes – error-404.html page for 404 Not Found, error-403.html page for 403 Forbidden, error-500.html page for 500 Internal Server, and error.html page otherwise.

That’s all about displaying custom error pages in Spring Boot.