当布尔 Mono 为特定值时抛出的一种更简洁的方法

A less verbose way to throw when a boolean Mono is a certain value

我有很多情况,布尔变量开始一个反应序列,如果它们是某个值(大部分是 false),应该抛出异常并破坏序列。例如

Mono.just(foo.isValid())
    .flatMap(b -> b ? Mono.empty() : Mono.error(new FooNotValidException(foo.detail1, foo.detail2)))
    .then(bar.doProcess())
    .flatMap(b -> b ? Mono.empty() : Mono.error(new BarProcessingNotSuccessful(bar.detail1, bar.detail2)))
    ....

此处如果 foo 无效,则不执行 bar 并且序列因详细异常而中断,如果 bar 处理失败则相同。

上面是我设法做到的最短的,但是有很多重复,所以我想知道是否可以减少它的冗长程度?

根据 Borises 的评论,我将上面的代码示例重写为

Mono.fromRunnable(foo::isValidOrThrow) // may throw FooNotValidException    
    .then(Mono.fromRunnable(bar::doProcessOrThrow)) // may throw BarProcesingNotSuccessful 
    ....

这看起来好多了。