Spring Boot - Custom Error Pages
Last Updated :
28 Aug, 2024
In web applications, a generic error page is typically displayed when a server error occurs or when a user tries to access a non-existent page. These default pages may not be user-friendly and can lead to a poor user experience. Spring Boot allows us to customize these error pages to make them more informative and visually appealing. Custom error pages can give users better feedback and guide them to take appropriate actions, such as returning to the homepage or contacting support.
Custom Error Pages in Spring Boot
Spring Boot provides a default mechanism for handling errors and displaying error pages. However, you can override this default behavior by defining our own error pages. This can be achieved by:
- Creating custom HTML error pages for different HTTP status codes.
- Configuring these error pages in the application properties file.
- Optionally, customizing the error response structure with the
@ControllerAdvice
class.
Prerequisites:
- Basic understanding of Java and Spring Boot.
- Familiarity with Thymeleaf (optional).
- Maven for dependency management.
- JDK and IntelliJ IDEA installed on your system.
Implementation of the Custom Error Page in a Spring Boot Application
Step 1: Create the Spring Boot Project
Create a new Spring Boot project using IntelliJ IDEA with the following options:
- Name:
spring-boot-custom-error-pages
- Language: Java
- Type: Maven
- Packaging: Jar
Click on the Next button.
Step 2: Add Dependencies
Add the following dependencies into the Spring Boot project.
Project Structure
After creating the project, the file structure should look like this:
Step 4: Configure the Application Properties
Open the application.properties
file and specify the configuration for custom error pages:
spring.application.name=spring-boot-custom-error-pages
# Disable the default Spring Boot error page
server.error.whitelabel.enabled=false
# Set the path for the custom error pages
server.error.path=/error
Step 5: Create the CustomErrorController Class
Create a controller class to customize the JSON response for RESTful APIs using the @ControllerAdvice annotation.
Java
package com.gfg.springbootcustomerrorpages;
import lombok.Data;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
/**
* ControllerAdvice for handling global exceptions and providing custom error responses.
*/
@ControllerAdvice
public class CustomErrorController extends ResponseEntityExceptionHandler {
/**
* Handles all exceptions and returns a custom error response.
*
* @param ex the exception
* @return ResponseEntity with error details
*/
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex) {
// Create a custom error response
ErrorResponse error = new ErrorResponse("Server Error", ex.getLocalizedMessage());
return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Error response structure for custom error messages.
*/
@Data
class ErrorResponse {
private String error;
private String message;
/**
* Constructor for creating an error response.
*
* @param error the error title
* @param message the error message
*/
public ErrorResponse(String error, String message) {
this.error = error;
this.message = message;
}
}
This class uses @ControllerAdvice
to handle exceptions globally and return custom JSON error responses. The ErrorResponse
class defines the structure of the error response.
Step 6: Main Class
No changes are required in the main class.
Java
package com.gfg.springbootcustomerrorpages;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Main class for running the Spring Boot application.
*/
@SpringBootApplication
public class SpringBootCustomErrorPagesApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCustomErrorPagesApplication.class, args);
}
}
This is the entry point of the Spring Boot application. It starts the application using SpringApplication.run()
.
Step 7: Create the Custom Error Pages
In the src/main/resources/templates directory, create the custom error pages. We willcreate the error-404.html and error-500.html for 404 Not Found and 500 Internal Server Error.
error.html:
HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Error</title>
<link rel="stylesheet" th:href="@{/css/styles.css}" />
</head>
<body>
<div class="error-container">
<h1>An Error Occurred</h1>
<p>We're sorry, but something went wrong.</p>
<a href="/" class="btn">Return to Home</a>
</div>
</body>
</html>
error-404.html:
HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Page Not Found</title>
<link rel="stylesheet" th:href="@{/css/styles.css}" />
</head>
<body>
<div class="error-container">
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
<a href="/" class="btn">Return to Home</a>
</div>
</body>
</html>
error-500.html
HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Internal Server Error</title>
<link rel="stylesheet" th:href="@{/css/styles.css}" />
</head>
<body>
<div class="error-container">
<h1>500 - Internal Server Error</h1>
<p>Something went wrong on our end. Please try again later.</p>
<a href="/" class="btn">Return to Home</a>
</div>
</body>
</html>
These HTML files provide user-friendly error pages for different status codes (404 and 500). They use Thymeleaf for rendering and include a link to return to the homepage.
Step 8: Create the CSS File for Styling
In the src/main/resources/static/css
directory, create a CSS file to style the error pages.
styles.css:
CSS
.error-container {
text-align: center;
padding: 50px;
font-family: Arial, sans-serif;
}
h1 {
font-size: 36px;
color: #ff6b6b;
}
p {
font-size: 18px;
margin: 20px 0;
}
a.btn {
text-decoration: none;
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border-radius: 5px;
}
This CSS file styles the error pages to ensure they are visually appealing and provide a good user experience.
pom.xml file:
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gfg</groupId>
<artifactId>spring-boot-custom-error-pages</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-custom-error-pages</name>
<description>spring-boot-custom-error-pages</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 9: Run the Application
Once the project is complete, start the application. It will run on port 8080.
Step 10: Testing the Custom Error Pages
To test the custom error pages, access non-existent URLs. For example, try accessing following URL to see the custom 404 error page.
http://localhost:8080/error
Output:
This example project demonstrates how to create the custom error pages in the Spring Boot application. It improves the user experience by providing clear, informative and visually appealing the error pages.
Similar Reads
Spring Boot - Customize Whitelabel Error Page In the Spring Boot ecosystem, when there is no custom error page to handle a specific error, Spring Boot by default handles the error with the help of the Whitelabel error page. This is the default Whitelabel error page. We can also customize this whitelabel error page. In this article, let us discu
4 min read
Spring Boot - @Requestmapping Spring Boot is the most popular framework of Java for building enterprise-level web applications and back-ends. Spring Boot has a handful of features that support quicker and more efficient web app development. Some of them are Auto-configuration, Embedded Server, opinionated defaults, and Annotatio
6 min read
Custom Endpoints in Spring boot Actuator Custom Endpoints in Spring Boot Actuator extends the default functionality provided by the Actuator. It involves defining a custom endpoint class annotated with @Endpoint, which contains methods annotated with @ReadOperation, @WriteOperation, and @DeleteOperation to handle GET, POST, and DELETE requ
4 min read
Next.js Custom Error Page Creating a custom error page in Next.js allows you to provide a better user experience when an error occurs, such as a 404 (Not Found) or a 500 (Server Error). Custom error pages can match your site's design and offer helpful information or navigation options. In this article, we will learn how to c
7 min read
Custom WebFlux Exceptions in Spring Boot 3 The Spring WebFlux is part of Spring Framework and it allows us for Reactive programming it supports Non Blocking I/O operations. The Spring Framework provides a lot of Annotations to handle the applications. In this article, we focus on Custom WebFlux Exceptions in Spring Boot 3 by using Rest API i
4 min read