Java 如何在SpringWebFlux@ExceptionHandler中访问RequestBody?

Java 如何在SpringWebFlux@ExceptionHandler中访问RequestBody?,java,spring,spring-boot,spring-webflux,Java,Spring,Spring Boot,Spring Webflux,是否有一种方法可以使用SpringWebFlux在@ExceptionHandler方法中使用默认的Reactor Netty访问RequestBody(最好是以其映射形式) 考虑以下示例: @RestController class TestRestController { @PostMapping("/test") Mono<TestBody> testPost(@RequestBody TestBody testBody) { return Mono.erro

是否有一种方法可以使用SpringWebFlux在
@ExceptionHandler
方法中使用默认的Reactor Netty访问
RequestBody
(最好是以其映射形式)

考虑以下示例:

@RestController
class TestRestController {

  @PostMapping("/test")
  Mono<TestBody> testPost(@RequestBody TestBody testBody) {
    return Mono.error(new NullPointerException());
  }

  @ExceptionHandler(NullPointerException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  Mono<Void> handleNullPointerException(ServerWebExchange serverWebExchange) {
    return Mono.empty();
  }

}
@RestController
类TestRestController{
@后映射(“/test”)
Mono testPost(@RequestBody TestBody){
返回Mono.error(新的NullPointerException());
}
@ExceptionHandler(NullPointerException.class)
@ResponseStatus(HttpStatus.BAD_请求)
Mono handleNullPointerException(服务器WebExchange服务器WebExchange){
返回Mono.empty();
}
}
在运行时,可以将的其他实例注入到
@ExceptionHandler
的方法签名中,如上面的
ServerWebExchange
示例所示。但是文档明确声明它不支持请求主体参数(参见中的注释)


使用Servlet堆栈,您可以将
RequestContext
注入为。WebFlux堆栈是否有一种等效或类似的方法?

是的,有一种方法,但不是一种真正好看的方法。我们也遇到了类似的问题,但在我们的例子中,我们希望能够访问被动上下文,因为我们顽固地选择在这种被动范式中使用MDC,所以MDC依赖于这种上下文

在使用异常处理程序和控制器建议进行了大量的来回操作之后,很明显,这里无法访问反应上下文

因此,我们扩展了AbstractErrorWebExceptionHandler。这里有一个句柄(ServerWebExchange,Throwable Throwable)方法,当您的应用程序出现错误时,将调用该方法。好的方面是有服务器WebExchange,您可以访问如下上下文:exchange.getAttributes().get(MDC_上下文)或类似以下正文:exchange.getRequest().getBody()


这样就解决了我们的MDC问题,但不幸的是,错误的映射必须手动处理。我记得我们投入了很多时间,那时候,这是最好的解决方案。干杯

我认为如果您从异常处理程序返回Mono/Flux,那么您就可以访问Reactor上下文。在我们的例子中,我们需要在ExceptionHandler方法中访问上下文,以便获取MDC并使用属于特定请求的correlationID记录错误消息。这是否回答了您的问题?