🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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:
CustomErrorAttributesextendsDefaultErrorAttributesto override thegetErrorAttributesmethod.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/helloendpoint.- Throws a
RuntimeExceptionif thenameparameter 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
- Open a web browser and navigate to
http://localhost:8080/hellowithout thenameparameter. - 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment