如何在执行 Flux.map() 时处理错误
2022-09-01 09:29:50
我试图弄清楚在Flux中映射元素时如何处理错误。
例如,我正在将 CSV 字符串解析到我的一个业务 POJO 中:
myflux.map(stock -> converter.convertHistoricalCSVToStockQuotation(stock));
其中一些行可能包含错误,因此我在日志中得到的是:
reactor.core.publisher.FluxLog: onNext([SOME_BOGUS_QUOTE]@38.09 (Fri Apr 08 00:00:00 CEST 2016) H(38.419998)/L(37.849998)/O(37.970001))
reactor.core.publisher.FluxLog: onNext([SOME_BOGUS_QUOTE]@38.130001 (Thu Apr 07 00:00:00 CEST 2016) H(38.189999)/L(37.610001)/O(37.799999))
reactor.core.publisher.FluxLog: onError(java.lang.IllegalArgumentException: Invalid CSV stock quotation: SOME_BOGUS_QUOTE,trololo)
reactor.core.publisher.FluxLog: java.lang.IllegalArgumentException: Invalid CSV stock quotation: SOME_BOGUS_QUOTE,trololo
我在API中阅读了一些错误处理方法,但大多数都提到返回“错误值”或使用回退通量,如下所示:
Flux.onErrorResumeWith(myflux, x -> Mono.fromCallable(() -> ... do stuff);
但是,将此与我一起使用意味着整个通量再次被处理。myflux
那么,有没有办法在处理特定元素时处理错误(即忽略它们/记录它们)并继续处理其余的通量?
使用@akarnokd解决方法进行更新
public Flux<StockQuotation> getQuotes(List<String> tickers)
{
Flux<StockQuotation> processingFlux = Flux.fromIterable(tickers)
// Get each set of quotes in a separate thread
.flatMap(s -> Mono.fromCallable(() -> feeder.getCSVQuotes(s)))
// Convert each list of raw quotes string in a new Flux<String>
.flatMap(list -> Flux.fromIterable(list))
// Convert the string to POJOs
.flatMap(x -> {
try {
return Flux.just(converter.convertHistoricalCSVToStockQuotation(x));
}
catch (IllegalArgumentException ex){
System.out.println("Error decoding stock quotation: " + x);
return Flux.empty();
}
});
return processingFlux;
}
但是,这可以作为一种魅力,因为您可以看到代码不如以前那么优雅。Flux API 没有任何方法来执行此代码执行的操作吗?
retry(...)
retryWhen(...)
onErrorResumeWith(...)
onErrorReturn(...)