Spring Boot
Whitelabel Error Page
Error Handling
Java
Web Development

Spring Boot Remove Whitelabel Error Page

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Spring Boot is a powerful framework for building Java applications, particularly suited for microservices architecture. One of its features is a default error page known as the "Whitelabel Error Page." Though useful for debugging during development, it might not be ideal for production environments where a more customized error handling solution is preferred. This article delves into the methods of removing or customizing the Whitelabel Error Page in Spring Boot applications.

Understanding the Whitelabel Error Page

The Whitelabel Error Page is a generic error page presented when an uncaught exception occurs, and no custom error handling is in place. It provides information like the error status, path, and an optional message. This default error page aims to aid developers in debugging but may expose implementation details of the application, thus potentially posing a security risk in production.

Disabling the Whitelabel Error Page

To disable the Whitelabel Error Page in a Spring Boot application, you can adjust the application.properties file by setting the server.error.whitelabel.enabled property to false:

properties
server.error.whitelabel.enabled=false

By doing this, errors will not display any specific error page; instead, the server will return a generic error code. Though it disables the default behavior, you are encouraged to provide a custom implementation for handling errors gracefully.

Customizing Error Pages

Using ErrorController

The recommended way to customize error pages in Spring Boot applications is by implementing the ErrorController interface. This interface provides the getErrorPath() method, which defines the path triggered in case of an error. A simple implementation would look like this:

java
1import org.springframework.boot.web.servlet.error.ErrorController;
2import org.springframework.stereotype.Controller;
3import org.springframework.web.bind.annotation.RequestMapping;
4import javax.servlet.http.HttpServletResponse;
5
6@Controller
7public class CustomErrorController implements ErrorController {
8
9    private static final String ERROR_PATH = "/error";
10
11    @RequestMapping(ERROR_PATH)
12    public String handleError(HttpServletResponse response) {
13        // Customize error handling here
14        int status = response.getStatus();
15        if (status == HttpServletResponse.SC_NOT_FOUND) {
16            return "error-404";
17        } else if (status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
18            return "error-500";
19        }
20        return "error";
21    }
22
23    @Override
24    public String getErrorPath() {
25        return ERROR_PATH;
26    }
27}

ErrorViewResolver

Another approach is implementing the ErrorViewResolver interface, which allows more control over the error views. This can be beneficial if you want to resolve views based on specific exception types, HTTP status codes, or other attributes.

java
1import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
2import org.springframework.stereotype.Component;
3import org.springframework.web.servlet.ModelAndView;
4
5import javax.servlet.http.HttpServletRequest;
6import org.springframework.http.HttpStatus;
7import java.util.Map;
8
9@Component
10public class CustomErrorViewResolver implements ErrorViewResolver {
11
12    @Override
13    public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
14        if (status == HttpStatus.NOT_FOUND) {
15            return new ModelAndView("error-404", model);
16        } else if (status == HttpStatus.INTERNAL_SERVER_ERROR) {
17            return new ModelAndView("error-500", model);
18        }
19        return new ModelAndView("error", model);
20    }
21}

Handling Errors with @ControllerAdvice

Spring Boot also allows global exception handling using the @ControllerAdvice annotation. This approach involves defining methods for handling specific exceptions or HTTP status codes globally.

java
1import org.springframework.ui.Model;
2import org.springframework.web.bind.annotation.ControllerAdvice;
3import org.springframework.web.bind.annotation.ExceptionHandler;
4import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
5import org.springframework.http.ResponseEntity;
6
7import java.util.NoSuchElementException;
8
9@ControllerAdvice
10public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
11
12    @ExceptionHandler(NoSuchElementException.class)
13    public String handleNoSuchElementException(NoSuchElementException ex, Model model) {
14        model.addAttribute("message", ex.getMessage());
15        return "error-404";
16    }
17
18    @ExceptionHandler(Exception.class)
19    public String handleGeneralException(Exception ex, Model model) {
20        model.addAttribute("message", ex.getMessage());
21        return "error";
22    }
23}

Comparison Table of Error Handling Approaches

Below is a summary table comparing the different methods for handling or customizing errors in Spring Boot applications:

MethodDescriptionAdvantagesDisadvantages
Whitelabel ErrorDefault error page provided by Spring BootEasy to use and informative for debuggingNot secure for production usage
Disabling WhitelabelDisables Whitelabel Error Page with propertiesSimple configurationProvides no error detail to users
ErrorControllerCustomizes error page by implementing an interfaceFlexible and easy to customizeRequires extra code for customization
ErrorViewResolverAllows custom error views based on various attributesSupports complex error handling logicMore complex setup needed
@ControllerAdviceGlobal exception handling with specific methodsCentralized error handlingMay become complex with multiple exceptions

Conclusion

The Whitelabel Error Page offers a helpful starting point during the development of Spring Boot applications; however, it is not suitable for production due to potential security concerns. To implement robust and user-friendly error handling, developers can opt for disabling the default error page and adopting custom error controllers, view resolvers, or global exception advice. Integrating these solutions can lead to more secure and maintainable Spring Boot applications.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.