Spring Boot Customize Error Pages

Spring Boot: Customize Error Pages

Learn how to customize error pages in Spring Boot for a better user experience. Follow step-by-step instructions with examples.

1. Introduction

In the world of web development, user experience reigns supreme. One often-overlooked aspect of user experience is error handling. When users encounter errors on a website, they can be frustrated if the error pages are generic and unhelpful. In this guide, we’ll explore how to customize error pages in a Spring Boot application, ensuring a smoother user experience and a more professional appearance.

If you are specifically interested in modifying API responses for 404 errors, you can check out our blogs:

  • Spring Boot: Customize 404 Error Responses for Pre-Context Path URLs: Delve into customizing 404 error responses specifically for pre-context path URLs. Read more.
  • Enhancing API Error Responses: How to Customize 404 Not Found Response in Spring Boot: Focuses on enhancing API error responses, with an emphasis on customizing the 404 Not Found response. Explore here.


2. Understanding Error Handling in Spring Boot

By default, Spring Boot provides a whitelabel error page for handling various HTTP status codes. However, these default error pages lack customization and may not align with your application’s design and branding. Customizing error pages allows you to provide personalized and informative messages to users when errors occur.

3. How to Customize Error Pages in Spring Boot

Let’s understand the steps that are necessary to customize error pages effectively in Spring Boot.

Step 1: Disabling the Whitelabel Error Page

Let’s begin by understanding how to disable the default white label error page in Spring Boot. One approach is to set the server.error.whitelabel.enabled property to false in the application.properties file

server.error.whitelabel.enabled=false
application.properties

By making this change, we effectively turn off the default error page, allowing a concise page from the underlying application container, such as Tomcat, to be displayed instead.

Another method to disable the white label error page involves excluding the ErrorMvcAutoConfiguration bean. This can be done by adding the spring.autoconfigure.exclude property to application.properties and specifying the class path of the bean (org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration).

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration

# Spring Boot 2.0
# spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
application.properties

Alternatively, you can opt for using the @EnableAutoConfiguration annotation in the main class and excluding the ErrorMvcAutoConfiguration bean explicitly. This method provides flexibility and control over error handling within your Spring Boot application.

@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
SpringBootCustomizeErrorPagesApplication.class

All of these methods effectively disable the white label error page, prompting the question of how errors are managed afterward. Typically, error handling is delegated to the underlying application container.

However, we can take customization further by creating custom error pages to replace the defaults. This customization allows us to deliver a personalized and informative experience to users when errors occur.



Step 2: Adding Thymeleaf Starter Template for Automatic Error Page Pickup

Add the Thymeleaf starter template dependency to your pom.xml file to enable automatic pickup of error HTML pages from the resources/templates and resources/templates/error folders:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
pom.xml

Thymeleaf will automatically detect and render error HTML pages placed in the resources/templates and resources/templates/error folders.

Step 3: Displaying Custom Error Pages

In Spring Boot, displaying custom error pages involves creating HTML files within the /templates directory. By default, Spring Boot BasicErrorController, using the Thymeleaf template engine, looks for an error.html file in this folder to display the error page.

However, if you create specific HTML files for different error codes (e.g., 404.html for 404 errors, 500.html for 500 errors) inside the /templates/error folder, Spring Boot, using the Thymeleaf template engine, will automatically pick up and display the corresponding HTML file based on the error code encountered.

HTML Files:

error.html (Generic Error Page):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Error</title>
</head>
<body>
    <h1>An error occurred!</h1>
    <p>We apologize for the inconvenience.</p>
</body>
</html>
error.html

404.html (Page Not Found):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>404 Not Found</title>
</head>
<body>
    <h1>404 Error: Page Not Found</h1>
    <p>The page you are looking for could not be found.</p>
</body>
</html>
404.html

500.html (Internal Server Error):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>500 Internal Server Error</title>
</head>
<body>
    <h1>500 Error: Internal Server Error</h1>
    <p>There was a problem with the server. Please try again later.</p>
</body>
</html>
500.html

Simply save these HTML files with their respective names (error.html, 404.html, 500.html) in the appropriate folders (/templates for error.html, /templates/error for 404.html and 500.html) of your Spring Boot project. When an error occurs, Spring Boot will automatically detect and display the appropriate error page based on the encountered error code, providing a more customized and informative experience for users.



Output:

Scenario 1: Only error.html in /templates Folder

Default Error Handling: When only the error.html file is present in the /templates folder of your Spring Boot application, it serves as the default error page. This page will be rendered for all types of errors encountered, providing a general error message and options for users to navigate.

Scenario 2: 404.html in /templates/error Folder

Specific Error Handling for 404 Errors: In this scenario, if a 404.html file is present in the /templates/error folder of your Spring Boot application, it becomes the specific error page for handling 404 errors. When a user encounters a 404 error (page not found), Spring Boot automatically renders the 404.html page instead of the default error page (error.html). This targeted approach ensures that users receive a tailored error message and guidance when navigating to non-existent pages.



4. Implementing Custom Error Controller

In Spring Boot, the default error handling mechanism lacks the ability to execute custom logic when errors occur. To overcome this limitation, we can create a custom error controller bean to replace the default one.

To implement a custom error controller, follow these steps:

Step-1: Define Error Handling Path: Set the server.error.path property in the application configuration to specify the custom path for error handling.
For example: server.error.path=/error

Step-2: Create ErrorController Class: Implement the ErrorController interface in a class, such as CustomErrorController, and annotate it with @Controller. This class will handle error requests and provide custom error responses.

Step-3. Handle Error Requests: Create a method, e.g., handleError(), annotated with @RequestMapping("/error"), to handle error requests directed to the specified path (/error). This method will execute custom logic and return the appropriate error page based on the error status code.

Here’s an example to display specific error pages for different error types:

server.error.path=/error
application.properties
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class CustomErrorController implements ErrorController {

    private final Logger log = LoggerFactory.getLogger(CustomErrorController.class);

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request) {
        log.info("============Inside Custom Error Handler===========");
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        if (status != null) {
            var statusCode = Integer.parseInt(status.toString());

            if (statusCode == HttpStatus.NOT_FOUND.value()) {
                log.info("============404 Error Encountered===========");
                return "404-error";
            } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                log.info("============500 Error Encountered===========");
                return "500-error";
            }
        }
        return "error";
    }
}
CustomErrorController.java

In the CustomErrorController class, error handling is customized based on different error status codes. When a specific error occurs, the controller looks for corresponding HTML files in the /templates directory to render custom error pages. Here’s a breakdown of the file naming conventions and folder specifications:

  1. 404 Error Handling:
    • For a 404 error, the controller looks for a file named 404-error.html in the /templates directory.
    • Example path: /templates/404-error.html
  2. 500 Error Handling:
    • For a 500 error, the controller looks for a file named 500-error.html in the /templates directory.
    • Example path: /templates/500-error.html
  3. Other Errors:
    • For any other errors not specifically handled (e.g., 403 Forbidden), the controller looks for a generic error file named error.html in the /templates directory.
    • Example path: /templates/error.html


Furthermore, you have the flexibility to organize your HTML files in nested subfolders within the /templates directory. You can specify these folder structures in the CustomErrorController when returning the response.

For instance:

  1. If the HTML file for a 404 error is present in the /templates/error folder, you can return it using the path /error/404-error. This allows for a structured organization of error pages.
  2. Similarly, if the HTML file for a 500 error is located in a subfolder named server-errors within the /templates/error folder, you can return it using the path /error/server-errors/500-error.


5. Source Code

The complete source code of the above examples can be found here.

6. Conclusion

In conclusion, customizing error pages in Spring Boot empowers developers to create tailored and informative error messages, enhancing user experience during unexpected scenarios.



7. Learn More

#

Interested in learning more?

Spring Boot: Customize 404 Error Responses for Pre-Context Path URLs



Add a Comment

Your email address will not be published.