Issue
In my Spring Boot application, I'm trying to configure custom error pages, for example for 404, I have added a following Bean to my application configuration:
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));
}
};
}
Also, I have created a following simple Thymeleaf template:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>404 Not Found</title>
<meta charset="utf-8" />
</head>
<body>
<h3>404 Not Found</h3>
<h1 th:text="${errorCode}">404</h1>
<p th:utext="${errorMessage}">Error java.lang.NullPointerException</p>
<a href="/" th:href="@{/}">Back to Home Page</a>
</body>
</html>
and added it into /resources/templates/
folder. Right now on the 404 error I can see only white screen.
What am I doing wrong and how to correctly setup my 404 page? Also, is it possible to use templates and not only static pages for custom error pages?
Solution
You're using Thymeleaf, And Thymeleaf can handle error without a controller.
For a generic error page this Thymeleaf page need to be named as error.html
and should be placed under src/main/resources > templates > error.html
For specific error pages, you need to create files named as the http error code in a folder named error, like: src/main/resources/templates/error/404.html
.
Answered By - GoutamS