Custom HTML Error Page using Thymeleaf Custom HTML Error Page using Thymeleaf

Page content

In this article, we’ll learn how to customize default Whitelabel Error Page in Spring Boot using Thymeleaf HTML templates

Whitelabel Error Page

Whitelabel error page is default error page generated by Spring Boot when no custom error page is provided.

If you don’t like this default behavior and looking for custom HTML pages to be displayed for different type of HTTP errors then Thymeleaf error templates are simplest approach to follow.

Thymeleaf Error Templates

You create Thymeleaf HTML error template under resources/templates directory:-

  1. Generic error template required with name error.html
  2. Specific error templates are optional under errors directory with name <error_code>.html for e.g. 404.html for Not found error, 500.html for Internal server error, etc.

Generic Error Template

If specific error template not found then fallback to generic template for all types of HTTP error codes.

<!DOCTYPE html>
<html xmlns:th="">
    <title>Something went wrong!</title>
  <h1>Generic Error - <span th:text="${status}">Status</span></h1>
  <p>Sorry for the inconvenience. Please contact the administrator.</p>
    <li>Timestamp: <span th:text="${timestamp}">Timestamp</span></li>
    <li>Path: <span th:text="${path}">Path</span></li>
    <li>Error: <span th:text="${error}">Error</span></li>

Specific error template 500.html doesn’t exist, display error.html

Specific Error Template

If specific error template found for e.g. 404.html, display it for 404 error!
We imported bootstrap css in the 404 error page to look more elegant.

<!DOCTYPE html>
<html xmlns:th="">
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Bootstrap -->
  <link rel="stylesheet" href="" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
  <title>404 - resource not found</title>
<div class="container">
  <h1><span class="label label-default">Resource Not Found Error - 404</span></h1>

  <p>Requested resource was not found. Please contact the administrator.</p>
  <table class="table table-bordered table-striped">
      <td th:text="${timestamp}">Timestamp</td>
      <td th:text="${path}">Path</td>
      <td th:text="${status}">Status</td>
      <td th:text="${error}">Error</td>
      <td th:text="${message}">Message</td>

Specific error template 400.html exist, display it!

Thymeleaf Dependency

We need to add Thymeleaf dependency in the project for these error templates to work.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

Thats it! Once you add Thymeleaf dependency, it does all the magic.