Spring Boot: Customize Whitelabel Error Page – Spring Boot 自定义白标签错误页面

最后修改: 2018年 4月 13日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we’re going to look at how to disable and customize the default error page for a Spring Boot application as proper error handling depicts professionalism and quality work.

在这篇文章中,我们将探讨如何禁用和自定义Spring Boot应用程序的默认错误页面,因为适当的错误处理描绘了专业性和高质量的工作。

2. Disabling the Whitelabel Error Page

2.禁用白标错误页面

First, let’s see how we can disable the white label error page entirely, by setting the server.error.whitelabel.enabled property to false:

首先,让我们看看如何通过将server.error.whitelabel.enabled属性设置为false来完全禁用白标错误页面:

server.error.whitelabel.enabled=false

Adding this entry to the application.properties file will disable the error page and show a concise page that originates from the underlying application container, e.g., Tomcat.

在application.properties文件中添加此条目将禁用错误页面,并显示一个源自底层应用程序容器的简洁页面,例如Tomcat。

We can achieve the same result by excluding the ErrorMvcAutoConfiguration bean. We can do this by either adding this entry to the properties file:

我们可以通过排除ErrorMvcAutoConfiguration bean来实现同样的结果。我们可以通过在属性文件中添加这个条目来实现。

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration

#for Spring Boot 2.0
#spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration

Or by adding this annotation to the main class:

或者通过向主类添加这个注解。

@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})

All the methods mentioned above will disable the white label error page. That leaves us with the question of who then actually handles the error?

上面提到的所有方法都将禁用白标错误页面。这就给我们留下了一个问题:那么谁来实际处理这个错误呢?

Well, as mentioned above, it’s usually the underlying application container. The good thing is we can further customize things by showing our custom error pages instead of all the defaults – this is the focus of the next section.

嗯,如上所述,这通常是底层的应用程序容器。好在我们可以进一步定制,显示我们的自定义错误页面,而不是所有的默认值–这是下一节的重点。

3. Displaying Custom Error Pages

3.显示自定义错误页面

We first need to create a custom HTML error page.

我们首先需要创建一个自定义的HTML错误页面。

We’ll save the file as error.html since we’re using Thymeleaf template engine:

我们将文件保存为error.html,因为我们使用Thymeleaf模板引擎。

<!DOCTYPE html>
<html>
<body>
<h1>Something went wrong! </h1>
<h2>Our Engineers are on it</h2>
<a href="/">Go Home</a>
</body>
</html>

If we save this file in resources/templates directory, it’ll automatically be picked up by the default Spring Boot’s BasicErrorController.

如果我们把这个文件保存在resources/templates目录下,它将自动被Spring Boot默认的BasicErrorController接收。

This is all we need to display our custom error page. With some styling, we’ll now have a much nicer looking error page for our users:

这就是我们需要显示的自定义错误页面。通过一些样式设计,我们现在将有一个更漂亮的错误页面给我们的用户。

 

Spring Boot Custom Error Page

We can be more specific by naming the file with the HTTP status code we want it used e.g. saving the file as 404.html in resources/templates/error means it’ll be used explicitly for 404 errors.

我们可以通过用我们希望使用的HTTP状态代码来命名文件,例如,在resources/templates/error中保存文件为404.html,意味着它将明确用于404错误。

3.1. A Custom ErrorController

3.1.一个自定义的ErrorController

The limitation so far is that we can’t run custom logic when errors occur. To achieve that, we have to create an error controller bean that’ll replace the default one.

到目前为止的限制是,当错误发生时,我们不能运行自定义逻辑。为了实现这一点,我们必须创建一个错误控制器bean,以取代默认的控制器。

For this, we have to create a class that implements the ErrorController interface. Additionally, we need to set the server.error.path property to return a custom path to call when an error occurred

为此,我们必须创建一个实现ErrorController接口的类。此外,我们需要设置server.error.path属性,以便在发生错误时返回一个自定义路径来调用

@Controller
public class MyErrorController implements ErrorController  {

    @RequestMapping("/error")
    public String handleError() {
        //do something like logging
        return "error";
    }
}

In the snippet above, we also annotate the class with @Controller and create a mapping for the path that is specified as the property server.error.path:

在上面的片段中,我们还用@Controller注释了该类,并为路径创建了一个映射,该映射被指定为属性server.error.path:/em>。

server.error.path=/error

This way the controller can handle calls to the /error path.

这样,控制器可以处理对/error路径的调用。

In the handleError(), we return the custom error page we created earlier. If we trigger a 404 error now, it’s our custom page that will be displayed.

handleError()中,我们返回我们先前创建的自定义错误页面。如果我们现在触发一个404错误,显示的将是我们的自定义页面。

Let’s further enhance the handleError() to display specific error pages for different error types.

让我们进一步加强handleError(),为不同的错误类型显示特定的错误页面。

For example, we can have nicely designed pages specifically for 404 and 500 error types. Then we can use the HTTP status code of the error to determine a suitable error page to display:

例如,我们可以有专门为404和500错误类型设计的精美页面。然后,我们可以使用错误的HTTP状态代码来确定一个合适的错误页面来显示。

@RequestMapping("/error")
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 "error-404";
        }
        else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
            return "error-500";
        }
    }
    return "error";
}

Then, for a 404 error, for example, we’ll see the error-404.html page:

然后,对于一个404错误,例如,我们会看到error-404.html页面。

error404

4. Conclusion

4.结论

With this information, we can go now handle errors more elegantly and show our users an aesthetic page.

有了这些信息,我们现在可以去更优雅地处理错误,向我们的用户展示一个美观的页面。

As always, the complete source code is available over on Github.

一如既往,完整的源代码可在Github上获得。