我不了解你们,但是对我来说,当我看到一段代码时,这变得非常烦人,repeated
并且在使用Services
该throw异常时遇到了以下情况。如下所示,在每个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
关于exception handling
内部supplyAsync lambda
?
只需将一个方法添加到您的类中即可执行所有重复的代码,并以a Consumer<List<?>>
作为参数传递给thenAcceptAsync
最后一行。
private CompletableFuture<Void> getAndAcceptAsync(Consumer<List<?>> resultProcessor) {
return CompletableFuture.supplyAsync(() -> {
List<SomePojo> somePojos = null;
try {
somePojos = someServiceThatThrowsException.getAll(SomePojo.class);
} catch (SomeException e) {
//Handle the exception
e.printStackTrace();
}
return somePojos;
}).thenAcceptAsync(resultProcessor);
}
然后,您可以根据需要多次拨打此电话。
future1Of15 = getAndAcceptAsync(result-> { do something } );
future2Of15 = getAndAcceptAsync(result-> { do something else } );
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句