我这里有这个功能:
Function<Integer, Integer> func = (value) -> value + 5;
func = func.andThen((value) -> {
//Imagine that here some code executed and raised an exception, I'm throwing it
//manually just for the sake of this example.
throw new RuntimeException("failed");
});
func = func.andThen((value) -> {
System.out.println("Reached last function !");
return value;
});
executeFunction(func);
现在,您可以看到我在第一个 andThen 方法中引发了运行时异常。那是因为我想阻止第二个 andThen 被执行。这是最好的方法吗?
此外,我注意到,如果我在不同的线程(异步)内执行此函数,则异常不会打印在我的控制台中,并且我想知道异常是否发生。
private static void executeFunction(Function<Integer, Integer> function) {
CompletableFuture.supplyAsync(() -> function.apply(100));
}
在这种情况下,如果我想确保记录异常,但 andThen 链中的下一个函数没有执行,我应该记录并抛出异常吗?这不是一个 ati 模式吗?
最佳答案
实例化和抛出大量异常可能会变得相当昂贵,这就是为什么它们应该仅限于异常情况。相反,您可以使用 Optional对于控制流:
func = (value) -> Optional.of(value + 5);
func = func.andThen((optionalValue) -> {
// Instead of throwing an exception, return an empty Optional
System.out.println("Log the failure");
return Optional.empty();
});
func = func.andThen((optionalValue) -> {
optionalValue.map((value) -> { // This lambda will only execute if optionalValue is not empty
System.out.println("Reached last function !");
return value; // map wraps this in an Optional
});
});
// Finally, unwrap the value. Optional provides a number of ways to do this, depending on how you want to handle failure/empty
func = func.andThen((optional) -> optional.orElse(...));
executeFunction(func);
关于java - 在异步执行时停止函数链执行的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58099672/