我有一个返回 CompletionStage<>
的方法在不同的点上,但似乎在 try-catch block 中这样做会导致“不兼容的类型”错误:
Incompatible types
Required: CompletionStage<com.foo.Response>
Found: CompletableFuture<? extends com.foo.Response>
这是代码。我已经尽可能地简化了它,但没有潜在地消除罪魁祸首:
public CompletionStage<Response> example(final Optional<String> idMaybe) {
return idMaybe.map(id -> {
if (true) { // Simplified example.
if (!NumberUtils.isNumber(id)) {
return CompletableFuture.completedFuture(Response.forStatus(Status.BAD_REQUEST));
}
final SomeServiceInterface service;
try {
service = someClient.getServiceInterface(SomeServiceInterface.class);
} catch (SomeException e) {
LOG.error("Error retrieving SomeServiceInterface.", e);
return CompletableFuture.completedFuture(Response.forStatus(Status.INTERNAL_SERVER_ERROR));
}
final Page page;
try {
page = someService.getSomethingByStatement(statementBuilder.toStatement());
} catch (RemoteException e) {
LOG.error("Error retrieving a thing by statement", e);
return CompletableFuture.completedFuture(Response.forStatus(Status.INTERNAL_SERVER_ERROR));
}
if (page.getResults() == null || page.getTotalResultSetSize() == 0) {
return CompletableFuture.completedFuture(Response.forStatus(Status.NOT_FOUND));
}
if (page.getTotalResultSetSize() != 1) {
// There should be only one result.
return CompletableFuture.completedFuture(Response.forStatus(Status.INTERNAL_SERVER_ERROR));
}
}
return CompletableFuture.completedFuture(Response.ok());
}).orElse(CompletableFuture.completedFuture(Response.forStatus(Status.BAD_REQUEST)));
}
为了缩小问题范围,我删除了失败案例 return
是一一向后的。首先,删除这个:
if (page.getTotalResultSetSize() != 1) {
// There should be only one result.
return CompletableFuture.completedFuture(Response.forStatus(Status.INTERNAL_SERVER_ERROR));
}
还是同样的错误。那么,删除这个:
if (page.getResults() == null || page.getTotalResultSetSize() == 0) {
return CompletableFuture.completedFuture(Response.forStatus(Status.NOT_FOUND));
}
还是同样的错误。那么,删除这个:
final Page page;
try {
page = someService.getSomethingByStatement(statementBuilder.toStatement());
} catch (RemoteException e) {
LOG.error("Error retrieving a thing by statement", e);
return CompletableFuture.completedFuture(Response.forStatus(Status.INTERNAL_SERVER_ERROR));
}
还是同样的错误。那么,删除这个:
final SomeServiceInterface service;
try {
service = someClient.getServiceInterface(SomeServiceInterface.class);
} catch (SomeException e) {
LOG.error("Error retrieving SomeServiceInterface.", e);
return CompletableFuture.completedFuture(Response.forStatus(Status.INTERNAL_SERVER_ERROR));
}
这消除了错误。 (我仔细检查了一下,这不是因为它在其他地方引起了错误;它可以编译。)
从 try-catch block 中返回可完成的 future 有什么不同?或者说,发生了什么事情使它看起来如此?我该如何修复原始代码?
最佳答案
我认为 @MạnhQuyếtNguyễn 在评论中的想法是正确的,但由于我无法轻松地按照他的方式构建代码,所以我找到了另一个解决方案:
return creativeIdMaybe.<CompletionStage<Response>>map(creativeId -> {
毕竟,我认为是 map
在解析类型时遇到了问题。 (我想。我不知道。)
关于java - 为什么从 try-catch block 内部返回 CompletableFuture.completedFuture(...) (似乎)会导致此错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50416156/