【发布时间】:2018-06-19 19:31:32
【问题描述】:
我不了解你们,但是对我来说,当我看到一段代码 repeated 时,我感到非常恼火,并且在使用抛出异常的 Services 时遇到了以下场景。如下所示,在每个CompletableFuture 块中,我必须执行exception handling 并且该部分基本上一遍又一遍地重复,具体取决于您将拥有多少可完成的期货。
CompletableFuture<Void> future1Of15 = CompletableFuture.supplyAsync(() -> {
List<SomePojo> somePojos = null;
try {
somePojos = someServiceThatThrowsException.getAll(SomePojo.class);
} catch (SomeException e) {
//Handle the exception
e.printStackTrace();
}
return somePojos;
}).thenAcceptAsync(result -> //do something with the result);
CompletableFuture<Void> future2Of15 = CompletableFuture.supplyAsync(() -> {
List<OtherPojo> otherPojos = null;
try {
otherPojos = someServiceThatThrowsException.getAll(OtherPojo.class);
} catch (SomeException e) {
//Handle the exception
e.printStackTrace();
}
return otherPojos;
}).thenAcceptAsync(result -> //do something with the result);
现在重复上面的x 次数,你注意到try/catch 块被重复了。就我而言,我有大约15-20 这样的电话。
有没有办法可以将上面的代码变成 1 或 2 行代码?换句话说,stop repeating myself 相对于supplyAsync lambda 内的exception handling?
【问题讨论】:
标签: java java-8 future dry completable-future