Chapter 30 - Transforming Spring Boot Errors into User-Friendly Experiences

Crafting a Smooth Journey: Transforming Generic Spring Boot Error Pages into Unique User-Centric Experiences

Chapter 30 - Transforming Spring Boot Errors into User-Friendly Experiences

Creating a web application that runs smoothly is crucial, but let’s be honest – errors happen. In Spring Boot, when things go awry, you get slapped with a Whitelabel error page by default. It’s like being handed a generic “404 Not Found” sign while wandering aimlessly in an unfamiliar town. Functional? Sure. User-friendly? Not so much. Getting rid of the Whitelabel error page and giving your application a personal touch with custom error handling can drastically improve the user experience and add polish to your application.

First thing’s first, let’s talk about that infamous Whitelabel error page. This page pops up when there’s no specific mapping for the /error endpoint. It gives you the HTTP status code and a bland error message. Think of it as your computer’s way of saying, “Oops, something went wrong,” without offering much other help. Now, wouldn’t it be better if, instead of this default page, your users landed on a custom page that says, “Sorry, looks like something went off track! But it’s okay, here’s what you can do”?

Spring Boot allows you to disable the Whitelabel error page. It’s as easy as flipping a switch in your application.properties or application.yml file:

server.error.whitelabel.enabled=false

Once you’ve disabled it, the server will show a raw, unstyled error page. Not the best in the looks department, but it’s a start.

The next step in sprucing things up is creating custom error pages. It’s pretty straightforward. Head over to your project structure and hop into the src/main/resources directory. Create a folder named templates and, inside, you can create various HTML error pages. Picture this: a custom 404.html and 500.html that reflects your app’s aesthetic. Here’s an example template for a 404.html:

<!DOCTYPE html>
<html>
<head>
    <title>404 Not Found</title>
    <meta charset="ISO-8859-1">
</head>
<body>
    <h3>Sorry, the page you are looking for does not exist.</h3>
    <a href="/" th:href="@{/}">Back to Home Page</a>
</body>
</html>

A neat little addition would be ensuring Spring Boot knows where to pick these templates up from. Here’s how you set it in the application.properties:

spring.mvc.view.prefix=/templates/
spring.mvc.view.suffix=.html

Now, if there’s a hiccup somewhere and an error occurs, instead of being greeted by the dull Whitelabel page, your users will see your carefully crafted custom error page.

And it gets even better! You can create specific custom error pages for different HTTP status codes, like 403.html for forbidden errors, neatly organized within a subfolder named error nestled snugly inside the templates directory. It could look something like this:

src/main/resources/templates/error/403.html
src/main/resources/templates/error/404.html
src/main/resources/templates/error/500.html

Whether it’s a minor misstep or a more significant crash, users will appreciate the attention to detail and the personalized messaging that keeps them in the loop.

Sometimes, merely presenting a nice facade isn’t enough. You’ve got to roll up your sleeves and do a bit more under the hood. Enter the custom error controller. If you want more control, like logging errors or zapping notifications to developers when something breaks, this is your jam.

You can set up a controller class to act when an error trips over the /error endpoint:

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        if (status != null) {
            int statusCode = Integer.parseInt(status.toString());

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

        return "error";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

For extra credit, ensure the custom error controller gets registered. Here’s a snippet of how that’s done:

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
    return new EmbeddedServletContainerCustomizer() {
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error"));
            container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error"));
        }
    };
}

With this setup, you’re not just slapping up an error page, you’re actively handling and responding to errors programmatically. That’s some next-level troubleshooting.

For those wanting an even finer degree of error management across the entire app, @ControllerAdvice is your secret weapon. This annotation lets you catch exceptions in one go, smoothing out any rough patches before users realize they’re there.

Here’s how you might set up a nifty global error handler:

@ControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<ErrorResponse> handleException(Exception ex) {
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setMessage(ex.getMessage());
        errorResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());

        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

class ErrorResponse {
    private String message;
    private int status;

    // Getters and setters
}

This approach is especially handy in RESTful APIs where your app gently breaks the bad news with detailed error responses instead of leaving users in the dark.

With these tools, crafting a smooth user experience in Spring Boot doesn’t just stop with happy-path coding. Giving errors a stylish, informative spin ensures users feel informed and reassured, even when tech gremlins strike.