Spring boot add custom error page to Thymeleaf

June 08, 2019 | No comments
This article shows how to replace the default error page with custom Thymeleaf error page in Spring boot.

We will first define a HTML file with name error.html, Here we have used bootstrap CSS for styling the page and added some of the informations like the timestamp, Date, Error etc. in the HTML page.
Spring boot provides default mapping for /error to which all exception or error responses are forwarded.

src/main/resources/templates/error.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<link rel="stylesheet" type="text/css" th:href="@{~/css/bootstrap.min.css}" />
<link rel="stylesheet" type="text/css" th:href="@{~/css/style.default.css}" />
</head>
<body marginwidth="0" marginheight="0">
  <div class="container">
    <div class="row">
      <h1>Thymeleaf Error Page</h1>
    </div>
    <div class="row">It apperrs Either something went wrong or the page
      doesn't exist anymore.....</div>
    <div class="row rowDesign">
      <div class="col-md-4 ml-auto">
        <span class="legend">Date</span>
      </div>
      <div class="col-md-8">
        <span th:text="${timestamp}"></span>
      </div>
    </div>
    <div class="row rowDesign">
      <div class="col-md-4 ml-auto">
        <span class="legend">Path</span>
      </div>
      <div class="col-md-8">
        <span th:text="${path}"></span>
      </div>
    </div>
    <div class="row rowDesign">
      <div class="col-md-4 ml-auto">
        <span class="legend">Error</span>
      </div>
      <div class="col-md-8">
        <span th:text="${error}"></span>
      </div>
    </div>
    <div class="row rowDesign">
      <div class="col-md-4 ml-auto">
        <span class="legend">Status</span>
      </div>
      <div class="col-md-8">
        <span th:text="${status}"></span>
      </div>
    </div>
    <div class="row rowDesign">
      <div class="col-md-4 ml-auto">
        <span class="legend">Message</span>
      </div>
      <div class="col-md-8">
        <span th:text="${message}"></span>
      </div>
    </div>
    <div class="row rowDesign">
      <div class="col-md-4 ml-auto">
        <span class="legend">Exception</span>
      </div>
      <div class="col-md-8">
        <span th:text="${exception}"></span>
      </div>
    </div>
    <div class="row rowDesign">
      <div class="col-md-4 ml-auto">
        <span class="legend">Trace</span>
      </div>
      <div class="col-md-8">
        <span th:text="${trace}"></span>
      </div>
    </div>
  </div>
</body>
</html>
src/main/resources/application.properties
server.error.include-stacktrace=always
Start the Server
mvn spring-boot:run
Now for any error pages our custom error page should be displayed. For instance for 404 (for a page that does not exist) it should display something like follows.


No comments :

Post a Comment

Please leave your message queries or suggetions.