Customizing Whitelabel Error Page in Spring Boot

Spring Boot provides a default error page, known as the Whitelabel Error Page, which is displayed when an exception occurs and no custom error handling is defined. This page is useful during development but not suitable for production environments. In this tutorial, we will learn how to customize the Whitelabel Error Page in a Spring Boot application.

Prerequisites

  • JDK 17 or later
  • Maven or Gradle
  • IDE (IntelliJ IDEA, Eclipse, etc.)

Step 1: Set Up a Spring Boot Project

1.1 Create a New Spring Boot Project

Use Spring Initializr to create a new project with the following dependencies:

  • Spring Web
  • Thymeleaf (optional for HTML templating)

Download and unzip the project, then open it in your IDE.

1.2 Configure application.properties

Set up the application properties for your project. This file is located in the src/main/resources directory.

# src/main/resources/application.properties

# Server port
server.port=8080

# Thymeleaf configuration (optional)
spring.thymeleaf.cache=false

Step 2: Create a Custom Error Page

To customize the error page, we need to create an HTML file named error.html in the src/main/resources/templates directory. This will override the default Whitelabel Error Page.

2.1 Create the error.html Page

Create a new HTML file named error.html in the src/main/resources/templates directory and add the following content:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Error</title>
</head>
<body>
    <h1>Something went wrong!</h1>
    <p th:text="'Error Code: ' + ${status}"></p>
    <p th:text="'Message: ' + ${error}"></p>
    <p th:text="'Exception: ' + ${exception}"></p>
    <p th:text="'Path: ' + ${path}"></p>
    <a th:href="@{/}">Go to Home Page</a>
</body>
</html>

Explanation:

  • th:text="'Error Code: ' + ${status}": Displays the HTTP status code.
  • th:text="'Message: ' + ${error}": Displays the error message.
  • th:text="'Exception: ' + ${exception}": Displays the exception message.
  • th:text="'Path: ' + ${path}": Displays the request path.

Step 3: Customize the Error Attributes

Spring Boot uses the DefaultErrorAttributes class to populate the error attributes. We can extend this class to customize the error attributes.

3.1 Create a Custom Error Attributes Class

Create a new class named CustomErrorAttributes in the com.example.demo.error package (create the package if it doesn't exist).

package com.example.demo.error;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.Map;

@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, options);

        // Customize the error attributes
        errorAttributes.put("customMessage", "Custom error message");
        errorAttributes.put("customAttribute", "Additional error info");

        return errorAttributes;
    }
}

Explanation:

  • CustomErrorAttributes extends DefaultErrorAttributes to override the getErrorAttributes method.
  • errorAttributes.put("customMessage", "Custom error message"): Adds a custom error message to the error attributes.
  • errorAttributes.put("customAttribute", "Additional error info"): Adds an additional custom attribute to the error attributes.

Step 4: Create a Simple Controller

4.1 Create the HelloController

Create a controller to handle incoming requests and deliberately throw an exception to test the custom error page.

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(@RequestParam(required = false) String name) {
        if (name == null) {
            throw new RuntimeException("Name parameter is missing");
        }
        return "Hello, " + name;
    }
}

Explanation:

  • @RestController: Marks the class as a REST controller.
  • @GetMapping("/hello"): Maps GET requests to the /hello endpoint.
  • Throws a RuntimeException if the name parameter is missing to trigger the custom error page.

Step 5: Running and Testing the Application

5.1 Run the Application

Run the Spring Boot application using your IDE or the command line:

./mvnw spring-boot:run

5.2 Test the Custom Error Page

  1. Open a web browser and navigate to http://localhost:8080/hello without the name parameter.
  2. You should see the custom error page with the custom error attributes.

Conclusion

In this tutorial, you have learned how to customize the Whitelabel Error Page in a Spring Boot application. We covered:

  • Setting up a Spring Boot project.
  • Creating a custom error page using Thymeleaf.
  • Customizing the error attributes by extending DefaultErrorAttributes.
  • Creating a simple controller to test the custom error page.

By following these steps, you can effectively customize the error handling in your Spring Boot applications to provide a better user experience.

Comments