我有一个返回
CompletionStage<>
在不同的点上,但在try-catch块中这样做似乎会导致“不兼容类型”错误:
不兼容的类型
要求:完成阶段<通用域名格式。福。回应>
找到:CompletableFuture<?扩展com。福。回应>
这是密码。我已经尽可能地简化了它,但没有潜在地消除罪魁祸首:
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块中返回一个完整的未来有什么不同?或者,是什么让它看起来如此?我如何修复原始代码?