# 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>
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET 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?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
