java - 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 是空的...
解决方案
如果将它们压缩到代码中,则可以像这样使用 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
);
推荐阅读
- java - EDITTEXT Android:需要控制光标位置(阻止或允许)
- swift - 如何将自定义对象数组从 SwiftVC 传递到 ObjCVC?
- javascript - nodejs encoding to base64 string is not working
- python - Python3 诅咒代码在管道中不起作用
- python - Pandas 加入两个 DataFrame,其中一个是数据透视表
- prolog - Prolog - 矩阵 N 乘 N,元素为 [1,...,N^2]
- mysql - SQL删除具有多于一列的重复值的行
- php - 可以在 Wordpress 中跳过 <-- nextpage --> 标记吗?
- python - Modeling swarm behaviour in python
- javascript - Why this ternary operator not working? (more below)