When it comes to handling errors in a SpringBoot application, the default Tomcat error page can be, well, let’s face it, boring and uninformative. But fear not, dear developer, for we can customize the error page based on the status code to provide a more user-friendly experience. In this article, we’ll dive into the world of error handling and explore how to create custom error pages that’ll make you the envy of all your developer friends.
Why Customize the Error Page?
Before we dive into the nitty-gritty, let’s talk about why customizing the error page is a good idea. The default Tomcat error page is, well, basic. It provides minimal information and can be confusing for users who may not be familiar with technical jargon. By customizing the error page, you can:
- Provide a more user-friendly experience by offering clear and concise explanations of the error.
- Brand your error page to match your application’s look and feel.
- Offer suggestions or solutions to common errors.
- Collect valuable feedback from users to improve your application.
Understanding SpringBoot’s Error Handling Mechanism
Before we start customizing, let’s take a look at how SpringBoot handles errors. By default, SpringBoot uses the DefaultErrorViewResolver
to resolve error views based on the status code. This means that when an error occurs, SpringBoot will look for a view with a specific name that matches the status code. For example, if a 404 error occurs, SpringBoot will look for a view named “404.html” in the /src/main/resources/templates/error/
directory.
If no custom error view is found, SpringBoot will fall back to the default Tomcat error page. But we don’t want that, do we? We want to create our own custom error pages that’ll make our application shine!
Creating Custom Error Pages
To create custom error pages, we’ll need to create a new view for each status code we want to handle. Let’s start by creating a new directory called /src/main/resources/templates/error/
in our SpringBoot project.
src main resources templates error
Next, we’ll create a new HTML file for each status code we want to handle. For example, let’s create a 404.html
file for 404 errors.
error 404.html
In our 404.html
file, we can add the following code:
<!DOCTYPE html> <html> <head> <title>404 Error - Page Not Found</title> </head> <body> <h1>Oh no! Page not found!</h1> <p>We're sorry, but the page you're looking for doesn't exist.</p> </body> </html>
Similarly, we can create custom error pages for other status codes, such as 500.html for internal server errors or 403.html for forbidden requests.
Using Thymeleaf Templates
If you’re using Thymeleaf as your templating engine, you can create error pages with even more flexibility. Let’s create a 404.html
file in our /src/main/resources/templates/error/
directory:
error 404.html
In our 404.html
file, we can add the following code:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>404 Error - Page Not Found</title> </head> <body> <h1>Oh no! Page not found!</h1> <p>We're sorry, but the page you're looking for doesn't exist.</p> <p>Error message: <span th:text="${error.message}"></span></p> </body> </html>
In this example, we’re using Thymeleaf’s th:text
attribute to display the error message.
Configuring SpringBoot to Use Custom Error Pages
Now that we’ve created our custom error pages, we need to configure SpringBoot to use them. We can do this by creating a new configuration class that extends WebServerFactoryCustomizer
.
@Component public class ErrorPageConfigurer implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> { @Override public void customize(ConfigurableWebServerFactory factory) { ErrorPageRegistry errorPageRegistry = factory.getErrorPageRegistry(); errorPageRegistry.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/404")); errorPageRegistry.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500")); } }
In this example, we’re adding two custom error pages: one for 404 errors and one for 500 internal server errors.
Overriding the Default Error View Resolver
By default, SpringBoot uses the DefaultErrorViewResolver
to resolve error views. However, we can override this behavior by creating a custom error view resolver.
@Bean public ErrorViewResolver errorViewResolver() { return new CustomErrorViewResolver(); }
In our custom error view resolver, we can specify the prefix and suffix for our error views:
public class CustomErrorViewResolver implements ErrorViewResolver { @Override public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, String viewName) { return new ModelAndView("error/" + status.value() + ".html"); } }
In this example, we’re resolving error views based on the status code. For example, if a 404 error occurs, we’ll resolve to the /error/404.html
view.
Testing Custom Error Pages
The final step is to test our custom error pages. We can do this by creating a test that simulates an error occurring in our application.
@RunWith(SpringRunner.class) @SpringBootTest public class ErrorPageTest { @Autowired private TestRestTemplate restTemplate; @Test public void test404Error() { ResponseEntity<String> response = restTemplate.getForEntity("/non-existent-resource", String.class); assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); } }
In this example, we’re testing our custom 404 error page by simulating a request to a non-existent resource.
Conclusion
And there you have it, folks! With these simple steps, you can create custom error pages that’ll make your SpringBoot application stand out from the crowd. Remember, error handling is an essential part of any application, and by customizing the error page, you can provide a better user experience and collect valuable feedback to improve your application.
Status Code | Error Page |
---|---|
404 | 404.html |
500 | 500.html |
403 | 403.html |
So, go ahead and get creative with your error pages! Your users will thank you.
Here is the FAQ page about customizing the error page based on the status instead of Tomcat default page with SpringBoot:
Frequently Asked Question
Get the answers to the most commonly asked questions about customizing error pages with SpringBoot!
How do I customize the error page in SpringBoot instead of using the default Tomcat page?
To customize the error page in SpringBoot, you can create a custom error page and configure it in the application.properties file. For example, you can create a error.html file in the src/main/resources/templates directory and then configure it in the application.properties file by adding the following line: error.whitelabel.enabled=true. This will override the default Tomcat error page with your custom error page.
How do I specify a custom error page for a specific HTTP status code in SpringBoot?
To specify a custom error page for a specific HTTP status code, you can create a separate HTML file for each status code and then configure it in the application.properties file. For example, to customize the error page for 404 errors, you can create a 404.html file in the src/main/resources/templates/error directory and then configure it in the application.properties file by adding the following line: error.pages.404=/error/404.
Can I use a template engine like Thymeleaf to customize the error page in SpringBoot?
Yes, you can use a template engine like Thymeleaf to customize the error page in SpringBoot. Thymeleaf provides a powerful way to create dynamic templates that can be used to generate custom error pages. You can create a Thymeleaf template for the error page and then use it to generate a custom error page that includes dynamic content.
How do I Internationalize (i18n) my custom error page in SpringBoot?
To Internationalize (i18n) your custom error page in SpringBoot, you can use the SpringBoot’s built-in i18n support. You can create separate error pages for each locale and then configure them in the application.properties file. For example, you can create an error_en.html file for English and an error_fr.html file for French, and then configure them in the application.properties file by adding the following lines: error.pages.404.en=/error/404_en and error.pages.404.fr=/error/404_fr.
Can I use a controller to handle custom error pages in SpringBoot?
Yes, you can use a controller to handle custom error pages in SpringBoot. You can create a custom error controller that handles the error requests and returns a custom error page. For example, you can create a ErrorController class that handles the error requests and returns a custom error page based on the status code.