Exceptions

@Controller@ControllerAdvice 类可以有 @ExceptionHandler 方法来处理来自控制器方法的异常。下面的示例包含这样一个处理程序方法:

@Controller and @ControllerAdvice classes can have @ExceptionHandler methods to handle exceptions from controller methods. The following example includes such a handler method: include-code::./SimpleController[indent=0]

异常可以与正在传播的顶级异常(即直接抛出的 IOException)匹配,或与顶级包装异常(例如,包含在 IllegalStateException 中的 IOException)内的直接原因匹配。

The exception can match against a top-level exception being propagated (that is, a direct IOException being thrown) or against the immediate cause within a top-level wrapper exception (for example, an IOException wrapped inside an IllegalStateException).

对于匹配异常类型,最好将目标异常声明为方法参数,如前一示例中所示。或者,该注解声明可缩小异常类型以匹配。我们通常建议在参数签名中尽可能具体并按顺序声明您的主要根异常映射。有关详细信息,请参见 @ControllerAdvice

For matching exception types, preferably declare the target exception as a method argument, as shown in the preceding example. Alternatively, the annotation declaration can narrow the exception types to match. We generally recommend being as specific as possible in the argument signature and to declare your primary root exception mappings on a @ControllerAdvice prioritized with a corresponding order. See the MVC section for details.

WebFlux 中的 @ExceptionHandler 方法支持与 @RequestMapping 方法相同的方法参数和返回值,但请求正文和 @ModelAttribute 相关的参数除外。

An @ExceptionHandler method in WebFlux supports the same method arguments and return values as a @RequestMapping method, with the exception of request body- and @ModelAttribute-related method arguments.

Spring WebFlux 中的 @ExceptionHandler 方法的支持由 @RequestMapping 方法的 HandlerAdapter 提供。有关更多详细信息,请参见 DispatcherHandler

Support for @ExceptionHandler methods in Spring WebFlux is provided by the HandlerAdapter for @RequestMapping methods. See DispatcherHandler for more detail.

Media Type Mapping

除了异常类型之外,@ExceptionHandler 方法还可以声明可生产的媒体类型。这允许根据 HTTP 客户端请求的媒体类型(通常在“Accept”HTTP 请求头中)来优化错误响应。

In addition to exception types, @ExceptionHandler methods can also declare producible media types. This allows to refine error responses depending on the media types requested by HTTP clients, typically in the "Accept" HTTP request header.

应用程序可以直接在注释中为同一异常类型声明可生产的媒体类型:

Applications can declare producible media types directly on annotations, for the same exception type: