Spring 5 Reactive中的HTTP响应异常处理 [英] HTTP Response Exception Handling in Spring 5 Reactive
问题描述
我正在使用带有WebFlux响应式启动程序的Spring Boot 2和Spring 5开发一些响应式微服务。
I'm developing some reactive microservices using Spring Boot 2 and Spring 5 with WebFlux reactive starter.
我面临以下问题:我想处理所有问题我从调用另一个REST服务收到的HTTP状态,并在收到一些错误的HTTP状态时引发异常。例如,当我调用一个端点并收到404 HTTP状态时,我想抛出一个异常,并在某些ExceptionHandler类中处理该异常,就像在Spring 4中使用 @的方式一样ControllerAdvice
。
I'm facing the following problem: I want to handle all HTTP Statuses that I receive from calling another REST Services and throws an exception when I receive some bad HTTP Status. For example, when I call an endpoint and I receive an 404 HTTP Status, I want to throw an exception and that exception to be handled in some ExceptionHandler class, just like the way it was in Spring 4 with @ControllerAdvice
.
执行此操作的正确方法是什么?希望能收到一些好的建议。
What is the right way to do this? Hope to receive some good suggestions.
推荐答案
这可以分为两个部分解决。
This can be addressed in two independent parts.
使用 WebClient
时,您可以从远程服务。默认情况下,所有 4xx
和 5xx
客户端响应都将变为 WebClientResponseException
。因此,您可以直接在WebFlux应用程序中处理这些异常。
When using WebClient
, you can receive HTTP 404 responses from remote services. By default, all 4xx
and 5xx
client responses will be turned into WebClientResponseException
. So you can directly handle those exceptions in your WebFlux app.
如果您只想将404响应转换为自定义异常,则可以执行以下操作:
If you'd like to turn only 404 responses into custom exceptions, you can do the following:
WebClient webClient = //...
webClient.get().uri("/persons/1")
.retrieve()
.onStatus(httpStatus -> HttpStatus.NOT_FOUND.equals(httpStatus),
clientResponse -> Mono.error(new MyCustomException()))
.bodyToMono(...);
这显然是根据每个客户致电完成的。
This is obviously done on a per client call basis.
您可以使用 ExchangeFilterFunction
以更可重用的方式实现相同目的,而您可以在 WebClient 上进行一次设置。 code>实例如下:
You can achieve the same in a more reusable way with an ExchangeFilterFunction
that you can set once and for all on a WebClient
instance like this:
WebClient.builder().filter(myExchangeFilterFunction)...
如何在WebFlux应用程序中处理自定义异常
使用Spring WebFlux带注释,您可以使用带有 @ExceptionHandler
注释的方法来处理异常(请参阅 Spring框架参考文档)。
How to handle custom exceptions in WebFlux apps
With Spring WebFlux with annotations, you can handle exceptions with methods annotated with @ExceptionHandler
(see Spring Framework reference documentation).
注意:可以使用 WebExceptionHandler
,但是它的级别很低,因为那里没有高级支持:您需要使用缓冲区手动编写响应威瑟任何对序列化的支持。
Note: using a WebExceptionHandler
is possible, but it's quite low level as you'll have no high-level support there: you'll need to manually write the response with buffers without any support for serialization.
这篇关于Spring 5 Reactive中的HTTP响应异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!