WebExceptionHandler:如何用Spring Webflux编写正文 [英] WebExceptionHandler : How to write a body with Spring Webflux

查看:495
本文介绍了WebExceptionHandler:如何用Spring Webflux编写正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过添加WebExceptionHandler来处理api的异常。
我可以更改状态代码,但是当我想更改响应的正文时会卡住:例如添加异常消息或自定义对象。

I want to handle the Exception of my api by adding a WebExceptionHandler. I can change the status code, but I am stuck when i want to change the body of the response : ex adding the exception message or a custom object.

有人有人吗?

我如何添加我的WebExceptionHandler:

How I add my WebExceptionHandler :

HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(toHttpHandler(routerFunction))
  .prependExceptionHandler((serverWebExchange, exception) -> {

      exchange.getResponse().setStatusCode(myStatusGivenTheException);
      exchange.getResponse().writeAndFlushWith(??)
      return Mono.empty();

  }).build();


推荐答案

WebExceptionHandler 的级别较低,因此您必须直接处理请求/响应交换。

WebExceptionHandler is rather low level, so you have to directly deal with the request/response exchange.

请注意:


  • Mono< Void> 返回类型应表示响应处理已结束;这就是为什么它应该连接到 Publisher 编写响应

  • 的原因,在这个级别上,您直接处理数据缓冲区(没有可用的序列化支持)

  • the Mono<Void> return type should signal the end of the response handling; this is why it should be connected to the Publisher writing the response
  • at this level, you're dealing directly with data buffers (no serialization support available)

您的 WebExceptionHandler 可能看起来像这样:

Your WebExceptionHandler could look like this:

(serverWebExchange, exception) -> {

  exchange.getResponse().setStatusCode(myStatusGivenTheException);
  byte[] bytes = "Some text".getBytes(StandardCharsets.UTF_8);
  DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
  return exchange.getResponse().writeWith(Flux.just(buffer));
}

这篇关于WebExceptionHandler:如何用Spring Webflux编写正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆