首页 > 解决方案 > Spring Webflux:当 Mono.zip 中的一个 Mono 为空时处理错误

问题描述

我的代码如下

public Mono<Ship> getShip() { 
    //... 
}

public Mono<Car> getCar() { 
    //... 
}

public Mono<ShipAndCar> getCombinedMono() {
    Mono<Ship> shipMono = getShip();
    Mono<Car> carMono = getCar();

    return Mono.zip(shipMono, carMono
                    (ship, car) -> return new ShipAndCar(ship, car);

}

作为两者getShip,并且getCar可以返回错误或空单声道。我想返回类似Mono.error(new Exception("Custom message"))消息取决于哪个 Mono 为空的地方。我怎么做?

如果我switchIfEmpty在 Mono.zip 之后添加一个,我将不知道哪个组件 Mono 是空的...

标签: javaspring-webfluxproject-reactor

解决方案


如果将它们压缩到代码中,则可以像这样使用 switchIfEmpty 运算符扩展每个输入单声道

        var carAndShip = Mono.zip(
                Optional.ofNullable(shipMono)
                        .orElseThrow(() -> new RuntimeException("ship is null"))
                        .switchIfEmpty(Mono.error(new RuntimeException("ship is empty"))),
                Optional.ofNullable(carMono)
                        .orElseThrow(() -> new RuntimeException("car is null"))
                        .switchIfEmpty(Mono.error(new RuntimeException("car is empty"))),
                ShipAndCar::new
        );



推荐阅读