努力弄清楚如何处理从被动请求中收到的异常并将其冒泡(正文和Http状态代码将是最低限度的信息)。
我希望使用提到的here的ExchangeFilterFunction,但似乎无法捕获错误。我知道它已通过方法注册并运行
public class MyExchangeFilterFunction implements ExchangeFilterFunction {
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
return next.exchange(request).onErrorMap(MyError.class, c -> new RuntimeException("Ow"));
}
}
注册过滤功能:
WebClient.builder().filter(new MyExchangeFilterFunction())...
转换成错误(因为我无法弄清楚如何冒泡):
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class MyError extends RuntimeException{
private Long timestamp;
private String path;
private Integer status;
private String error;
private String message;
}
--------更新-------
错误现在被最新代码抛出,但无法弄清楚如何将响应体堵塞到Flux / Mono错误中。
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
return next.exchange(request).map(cr -> {
if(cr.statusCode().isError()) {
return ClientResponse.from(cr).body(
Flux.error(new RuntimeException("OW"))
).build();
} else {
return cr;
}
});
}
答案 0 :(得分:0)
让Exception Handling Reactive更进一步。
return ClientResponse.from(cr)
.body(cr.body(BodyExtractors.toFlux(AnError.class))
.flatMap(err -> Flux.error(new PassThroughException(err))))
.build();
然后在WebExceptionHandler中:
AnError error;
if(ex instanceof PassThroughException) {
error = ((PassThroughException) ex).getAnError();
} else {
...
}
exchange.getResponse().setStatusCode(HttpStatus.resolve(error.getStatus()));
exchange.getResponse().getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
byte[] bite = null;
try {
bite = objectMapper.writeValueAsBytes(error);
} catch (JsonProcessingException jpe) {
log.error("Unable to write error to client: {}", ex, jpe);
}
return exchange.getResponse().writeWith(Flux.just(exchange.getResponse().bufferFactory().wrap(bite)));