> For the complete documentation index, see [llms.txt](https://jack80342.gitbook.io/spring-boot/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/27.-developing-web-applications/27.2-the-spring-webflux-framework/27.2.5-error-handling.md).

# 27.2.5 错误处理

Spring Boot提供了`WebExceptionHandler`，用一种明智的方式处理所有的错误。在处理顺序上，它的位置在WebFlux提供处理器之前。对于机器客户端，它会产生带有错误的详细描述（HTTP状态与异常信息）的JSON响应。对于浏览器客户端，“whitelabel”错误处理器会以HTML格式渲染相同的数据。你也可以提供你自己的HTML模版来显示错误（查看[下一章节](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-webflux-error-handling-custom-error-pages)）。

自定义这个特性的第一步时常需要使用现存的机制，但是替换或者添加错误的内容。为此，你可以添加`ErrorAttributes`类型的bean。

为了改变错误处理的行为，你可以实现`ErrorWebExceptionHandler`，并注册一个那种类型的bean定义。因为 `WebExceptionHandler`的级别相当低，Spring Boot提供了方便的`AbstractErrorWebExceptionHandler`，让你以WebFlux函数式方法处理错误，如下所示：

```java
public class CustomErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {

    // Define constructor here

    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {

        return RouterFunctions
                .route(aPredicate, aHandler)
                .andRoute(anotherPredicate, anotherHandler);
    }

}
```

你也可以直接继承`DefauLambdatErrorWebExceptionHandler`，并重写特定的方法。

**自定义错误页**

如果你想要给某个给定的状态码显示自定义的HTML错误页，你可以在`/error`文件夹下添加一个文件。错误页可以是静态的HTML（也就是，添加在任何的静态资源文件夹下面），或者使用模版构建。文件名应当是状态码，或者是一系列掩码。

比如，为了将`404`映射到一个静态HTML文件，你的文件夹结构将会如下：

```
src/
 +- main/
     +- java/
     |   + <source code>
     +- resources/
         +- public/
             +- error/
             |   +- 404.html
             +- <other public assets>
```

使用Mustache模版映射所有的`5xx`错误，你的文件夹结构将会如下：

```
src/
 +- main/
     +- java/
     |   + <source code>
     +- resources/
         +- templates/
             +- error/
             |   +- 5xx.mustache
             +- <other templates>
```
