1. 概述

本教程将学习如何禁用和自定义 Spring Boot 应用的默认错误页面,专业的错误处理能体现开发者的专业性和项目质量。

2. 禁用白标错误页面

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

server.error.whitelabel.enabled=false

application.properties 中添加该配置后,错误页面将被禁用,改由底层应用容器(如 Tomcat)返回简洁的错误页面。

另一种方式是排除 ErrorMvcAutoConfiguration Bean。可通过以下属性配置实现:

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

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

或在主类添加注解:

@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})

以上方法均能禁用白标错误页面。那么问题来了:错误由谁处理?答案通常是底层应用容器。好消息是我们可以进一步自定义,使用自定义错误页面替代默认页面——这正是下一节的重点。

3. 显示自定义错误页面

首先需要创建自定义 HTML 错误页面。

**使用 Thymeleaf 模板引擎时,将文件保存为 error.html**:

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

将该文件存放在 resources/templates 目录,Spring Boot 的默认 BasicErrorController 会自动识别它。

只需这些步骤即可显示自定义错误页面。添加样式后,用户将看到更美观的错误页面:

Spring Boot 自定义错误页面

进阶技巧:通过 HTTP 状态码命名文件可实现更精细控制。例如,在 resources/templates/error 目录下创建 404.html,该页面将专门用于 404 错误。

3.1. 自定义 ErrorController

当前局限是无法在错误发生时执行自定义逻辑。要实现此功能,需创建替代默认控制器的错误控制器 Bean。

需创建实现 ErrorController 接口的类,并配置 server.error.path 属性指定错误处理路径:

@Controller
public class MyErrorController implements ErrorController  {

    @RequestMapping("/error")
    public String handleError() {
        // 执行自定义逻辑(如记录日志)
        return "error";
    }
}

上述代码中,我们用 @Controller 注解类,并为 server.error.path 属性指定的路径创建映射:

server.error.path=/error

这样控制器就能处理 /error 路径的请求。handleError() 方法返回之前创建的自定义错误页面。现在触发 404 错误时,将显示自定义页面。

进一步优化 handleError() 以处理不同错误类型

例如,为 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";
}

当发生 404 错误时,将显示 error-404.html 页面:

404错误页面

4. 总结

通过以上方法,我们能更优雅地处理错误,为用户展示更美观的错误页面。完整源代码可在 GitHub 获取。


原始标题:Spring Boot: Customize Whitelabel Error Page

» 下一篇: JVM语言概览