WebExceptionHandler:如何使用Spring Webflux编写正文

前端之家收集整理的这篇文章主要介绍了WebExceptionHandler:如何使用Spring Webflux编写正文前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想通过添加WebExceptionHandler来处理我的api的异常.
我可以更改状态代码,但是当我想要更改响应的主体时,我会陷入困境:ex添加异常消息或自定义对象.

有人有例吗?

我如何添加我的WebExceptionHandler:

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

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

  }).build();
@H_301_12@
最佳答案
WebExceptionHandler的级别相当低,因此您必须直接处理请求/响应交换.

注意:

> Mono< Void>返回类型应表示响应处理的结束;这就是它应该连接到发布者编写响应的原因
>在此级别,您直接处理数据缓冲区(没有可用的序列化支持)

您的WebExceptionHandler可能如下所示:

(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));
}
@H_301_12@
@H_301_34@ 原文链接:https://www.f2er.com/spring/432562.html

猜你在找的Spring相关文章