Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Sunday, April 19, 2020

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

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

No comments:

Post a Comment

Please do not add any spam links in the comments section.