在我的请求处理程序中,如果传入accountId
无法转换为有效的ObjectId
我想捕获错误并发回有意义的消息;但是,这样做会导致返回类型不兼容,并且我无法弄清楚如何实现这个非常简单的用例。
My code:
@GetMapping("/{accountId}")
public Mono<ResponseEntity<Account>> get(@PathVariable String accountId) {
log.debug(GETTING_DATA_FOR_ACCOUNT, accountId);
try {
ObjectId id = new ObjectId(accountId);
return repository.findById(id)
.map(ResponseEntity::ok)
.switchIfEmpty(Mono.just(ResponseEntity.notFound().build()));
} catch (IllegalArgumentException ex) {
log.error(MALFORMED_OBJECT_ID, accountId);
// TODO(marco): find a way to return the custom error message. This seems to be currently
// impossible with the Reactive API, as using body(message) changes the return type to
// be incompatible (and Mono<ResponseEntity<?>> does not seem to cut it).
return Mono.just(ResponseEntity.badRequest().build());
}
}
The body(T body)
方法改变返回的类型Mono
所以它是(假设一个人只是发送一个String
) a Mono<ResponseEntity<String>>
;但是,将该方法的返回类型更改为Mono<ResponseEntity<?>>
也不起作用:
...
return Mono.just(ResponseEntity.badRequest().body(
MALFORMED_OBJECT_ID.replace("{}", accountId)));
因为它在另一个上给出了“不兼容类型”错误return
陈述:
error: incompatible types: Mono<ResponseEntity<Account>> cannot be converted to Mono<ResponseEntity<?>>
.switchIfEmpty(Mono.just(ResponseEntity.notFound().build()));
显然,将方法的返回类型更改为Mono<?>
可以,但是响应是序列化的 JSONResponseEntity
这不是我想要的。
我也尝试过使用onErrorXxxx()
方法,但它们在这里也不起作用,因为转换错误甚至在计算 Flux 之前就发生了,而且我只是收到带有空消息的“普通”400 错误。
我能想到解决这个问题的唯一方法是添加一个message
领域到我的Account
反对并返回那个,但这确实是一个可怕的黑客行为。