Adding Custom Error Pages in Spring Boot MVC Applications

In this tutorial, we show you how to add custom error pages in existing Spring boot MVC projects.

To display a custom error page in a Spring Boot and Thymeleaf application, just create a new Thymeleaf template called error.html inside the src/main/resources/templates/ folder. Spring Boot default BasicErrorController will automatically pick up this template and display it to the user whenever there is an error or exception.

Create error.html under resources/templates/ folder

Here is an example of a generic error.html page:

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>PageNotFound</title>
</head>
<body>
<h2>The requested page could not be found.</h2>
<p>Click <a href="#" th:href="@{/}">Home</a> to go to Home page</p>
</body>
</html>

Run your Spring boot application and enter any invalid URL: http://localhost:8080/invalid

display the above page in a browser.

Specific Error Pages

For specific error pages, you need to create files named the HTTP error code in a folder named error, like: -

  • src/main/resources/templates/error/403.html
  • src/main/resources/templates/error/404.html
  • src/main/resources/templates/error/500.html

/resources/templates/error/403.html

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Access Denied</title>
</head>
<body>
<div class="container">
    <div class="row">
        <h2>You are not authorized to access this page.</h2>
        <p>Click <a href="#" th:href="@{/}">Home</a> to go to Home page</p>
    </div>
</div>
</body>
</html>

/resources/templates/error/404.html

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>PageNotFound</title>
</head>
<body>
<h2>The requested page could not be found.</h2>
<p>Click <a href="#" th:href="@{/}">Home</a> to go to Home page</p>
</body>
</html>

/resources/templates/error/500.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>ServerError</title>
</head>
<body>

<div>
  <h2>There is some problem in processing your request.</h2>
  <p>Click <a href="#" th:href="@{/}">Home</a> to go to Home page</p>
</div>

</body>
</html>

If there are any errors such as 500, 404, or 401 then the above pages will be displayed in the browser.


Comments