gpt4 book ai didi

spring - 如何在Spring webflux WebExceptionHandlder中将消息写入http body

转载 作者:行者123 更新时间:2023-12-02 08:08:46 25 4
gpt4 key购买 nike

this post的帮助下,我通过自定义 WebExceptionHandler 在 Spring 5 WebFlux 应用程序中部分完成了异常处理工作,但是当我想将友好消息中的现有异常转换为客户端时,它不起作用。

我的自定义WebExceptionHandler如下所示,完整代码为here .

 WebExchangeBindException cvex = (WebExchangeBindException) ex;
Map<String, String> errors = new HashMap<>();
log.debug("errors:" + cvex.getFieldErrors());
cvex.getFieldErrors().forEach(ev -> errors.put(ev.getField(), ev.getDefaultMessage()));

log.debug("handled errors::" + errors);
try {
DataBuffer db = new DefaultDataBufferFactory().wrap(objectMapper.writeValueAsBytes(errors));
exchange.getResponse().setStatusCode(HttpStatus.UNPROCESSABLE_ENTITY);
exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
exchange.getResponse().writeWith(Mono.just(db));
return exchange.getResponse().setComplete();

} catch (JsonProcessingException e) {
e.printStackTrace();
return Mono.empty();
}

状态码设置正确,但响应内容长度为0。

最佳答案

在您的代码示例中,您正在调用两者:

// write the given data buffer to the response
// and return a Mono that signals when it's done
exchange.getResponse().writeWith(Mono.just(db));
// marks the response as complete and forbids writing to it
exchange.getResponse().setComplete();

由于您正在调用第一个并且没有任何内容订阅它,因此不会将任何内容写入响应。

您可以更新代码以具有:

exchange.getResponse().setStatusCode(HttpStatus.UNPROCESSABLE_ENTITY);
exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF);
return exchange.getResponse().writeWith(Mono.just(db));

关于spring - 如何在Spring webflux WebExceptionHandlder中将消息写入http body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48047645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com