$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,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,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,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,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://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8aTRhqO4QCvwQcUq8nwOkGNoWAK7SC82pFgKhvDKeFNMGFHgBvqJ5w5-C9huEFIk3tMmwLUn0-yDhYuHuIrEwayRaIPw4POfjx6xWnIr1vHNdAeN-RpphCy52GxpbsJAGt06vY5YPSM4/s640/default+whilelebel+error+page.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8aTRhqO4QCvwQcUq8nwOkGNoWAK7SC82pFgKhvDKeFNMGFHgBvqJ5w5-C9huEFIk3tMmwLUn0-yDhYuHuIrEwayRaIPw4POfjx6xWnIr1vHNdAeN-RpphCy52GxpbsJAGt06vY5YPSM4/s72-c/default+whilelebel+error+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