spring 如何将Mono〈ResponseEntity>转换< Object>为Mono〈ResponseEntity< Void>>

3lxsmp7m  于 2023-03-28  发布在  Spring
关注(0)|答案(1)|浏览(170)

嗨,我有一个返回Mono<ResponseEntity<Void>>的API,该API将调用另一个返回Mono<ResponseEntity<Object>>的API,如何将该另一个API的结果转换为Mono<ResponseEntity<Void>>

public Mono<ResponseEntity<Void>> api() {
    return anotherApi()
        .map(response -> ResponseEntity.ok().build())
        .onErrorReturn(ResponseEntity.badRequest().build());
}

如果我只有map,上面的工作,但不是当我添加onErrorReturn,它抱怨Type mismatch: cannot convert from Mono<ResponseEntity<Object>> to Mono<ResponseEntity<Void>>,为什么它成为Mono<ResponseEntity<Object>>

nzk0hqpo

nzk0hqpo1#

代码是正确的,这只是Java泛型无法正确推断类型。
可以显式提供类型

public Mono<ResponseEntity<Void>> api() {
    return anotherApi()
        .<ResponseEntity<Void>>map(response -> ResponseEntity.ok().build())
        .onErrorReturn(ResponseEntity.badRequest().build());
}

或将onErrorReturn向上移动一级

public Mono<ResponseEntity<Void>> api() {
    return anotherApi()
        .onErrorReturn(ResponseEntity.badRequest().build())
        .map(response -> ResponseEntity.ok().build());
}

相关问题