$show=/label

Spring Boot: Customize Whitelabel Error Page Step By Step With ErrorController

SHARE:

A quick guide to how to add custom error page in spring boot application. Example to disable the default error page and how to customize the Whitelabel error page.

1. Introduction


In this tutorial, We'll learn how to customize the error page in spring boot application. We are going to cover how to disable the default error page and how we can customize the Whitelabel error page.

By default, Spring Boot shows the Whitelabel error page for any server related errors. But, the default showed the error is not relevant to our application and what is the problem. Actually, We should not use this page in the production environment. So, We need to show our customized and maintenance message on the error page.

Dependencies required:


<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<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>

I am running all examples code with spring boot version 2.2.6 release.

2. Whitelabel Error Page


Writing example code to display the default Whitelabel error page.

@GetMapping("/error")
 public String getDefaultPage(@RequestHeader(name = "errorcode") String errorCode) {
  logger.info("error code : " + errorCode);
  return "error";
 }




default whilelebel error page



3. Disabling the Whitelabel Error Page


Disabling whilelabel page can be done in two ways using properties file and annotation.

We'll see one by one with related configurations needed.

3.1 application.properties file


Built-in error page is hidden by using the property "server.error.whitelabel.enabled" in application.properties file. Just set this flag to false to disable the default error page.

server.error.whitelabel.enabled=false

This will disable the default one and will try to find out our customized one.

3.2 Exclude ErrorMvcAutoConfiguration


Even the same can be achieved by using another property "spring.autoconfigure.exclude" in the config file as below.

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration

3.3 Using Annotation


There is another way rather than keeping an entry in the props file. Now, let us add to the main application class @EnableAutoConfiguration annotation by mentioning which to be ignored.


package com.javaprogram.custom.errors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;

import com.javaprogram.springbootapp.SpringBootAppApplication;

@SpringBootApplication(scanBasePackages = "com.javaprogram.custom.errors")
@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
public class CustomErrorApplication {

 private static Logger logger = LoggerFactory.getLogger(CustomErrorApplication.class);

 public static void main(String[] args) {
  logger.info("Container started.....");
  SpringApplication.run(SpringBootAppApplication.class, args);
 }

}

All the above are worked well without any errors. And also I did not get the tomcat server default page because I have used the custom error page in the templates folder.

4. Setting Up Custom Error Page


Configuring the custom error page is easy. Follow the below guidelines step by step.

We are using thymeleaf template. So, Please create all of these files under resources/templates folder.

Create error pages as below.

This is the default error page.

error.html

<!DOCTYPE html>
<html>
<body>
 <h1>Maintenance is in progress</h1>
 <h2>Our Support team is working on it.</h2>
 <p>
  <a href="/">Please visit soon.</a>
 </p>
</body>
</html>

404.html


<!DOCTYPE html>
<html>
<body>
 <h1>You are looking for a page is not found</h1>
 <p>
  <a href="/">Go Home</a>
 </p>
</body>
</html>

400.html


<!DOCTYPE html>
<html>
<body>
 <h1>Sorry, Unexpected high volume.</h1>

 <h2>Please give try after sometime.</h2>
 <p>
  <a href="/">Go Home</a>
 </p>
</body>
</html>


Create a Controller class and implement ErrorController interfaces which shows the use of requested files as below. ErrorController interface has an abstract method that needs to be implemented and provide the error files location. In our case, I have placed in error folder so given as "/error" If you are using another location, please provide it correctly. But I tried to give a different location but for me, it did not consider the location. So, used default "/error" location that worked.

package com.javaprogram.custom.errors.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;

import com.javaprogram.api.RequestHeadersAPI;

@Controller
public class CustomErrorController implements ErrorController {

 Logger logger = LoggerFactory.getLogger(RequestHeadersAPI.class);

 @GetMapping("/custom/error")
 public String getCustomError(@RequestHeader(name = "code") String errorCode) {

  logger.info("error code : " + errorCode);
  if ("400".equals(errorCode)) {
   return "400";
  } else if ("404".equals(errorCode)) {
   return "404";
  }

  return "error";
 }

 @Override
 public String getErrorPath() {
  logger.info("setting up the path for error pages.");
  return "/error";
 }

}


For testing purposes, I have passing error code as part of request header using @RequestHeader annotation.

We'll test the api using postman.

400 error code testing

custom-error-400-code


404 error code:

custom-error-404-code


Other error codes:

custom-error-503-code


Instead of sending the error code in the request, we can get the error code from the actual HTTP request.

 @GetMapping(value = "/custom/errors")
 public String handleError(HttpServletRequest request) {

  Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

  if (status != null) {

   Integer statusCode = Integer.valueOf(status.toString());

   if (statusCode == HttpStatus.NOT_FOUND.value()) {
    return "404";
   } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
    return "500";
   }
 
  return "error";
 }

5. Conclusion


In this article, We've seen how to set the custom error page in Spring Boot and how to hide the default Whitelabel error page.

All shows examples are shown in the GitHub

GitHub Code

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,14,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,80,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,77,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,10,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Spring Boot: Customize Whitelabel Error Page Step By Step With ErrorController
Spring Boot: Customize Whitelabel Error Page Step By Step With ErrorController
A quick guide to how to add custom error page in spring boot application. Example to disable the default error page and how to customize the Whitelabel error page.
https://1.bp.blogspot.com/-Z_paFI_65HE/XpvvHFk976I/AAAAAAAACeY/MgJOEtxiP10EDZGvRplqW_n98IbW1GSYACEwYBhgLKs4DAL1Ocqy7sIRNCGEiE88V3dxkcUNFmRRB-m8ZIQl7yU9GdNNJMWZVpWqwb2RTBDXx0pysmHPRPJ75swm3fmPEDTn2AFNytb5-2u_QNTL-Q4P9v3QgiIE8Y8eCIfUZUT1clyGrhg72Y1WlYYq67s5ANUq0PG-Ko113vHivg8tPzLF7kt34RQmSXv3RUtxr_xTZb1J4vAjuDAFL_Q7YyPUZ0OsrYbk9aG238DSLyZqS5f96MhlJN9GNCiC1Y8BmSOavKVERBEpOqtrLtq4s2nKg86VCNV4Bi3loYH__Mv1yLJnQlaaTdIb0Eu-aGTU5NPTi34rmsa4UT0w_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page.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/04/spring-boot-custom-error-page.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/04/spring-boot-custom-error-page.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content