如何从 Akka Streams Sink 抛出的异常中恢复?
How to recover from Exception thrown in Akka Streams Sink?
如何从 Akka Streams 的 Sink 抛出的异常中恢复?
简单示例:
Source<Integer, NotUsed> integerSource = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
integerSource.runWith(Sink.foreach(x -> {
if (x == 4) {
throw new Exception("Error Occurred");
}
System.out.println("Sink: " + x);
}), system);
输出:
Sink: 1
Sink: 2
Sink: 3
如何处理异常并从源转到下一个元素? (又名 5、6、7、8、9)
默认情况下,supervision strategy 在抛出异常时停止流。要更改监管策略以删除导致异常的消息并继续处理下一条消息,请使用 "resume" 策略。例如:
final Function<Throwable, Supervision.Directive> decider =
exc -> {
return Supervision.resume();
};
final Sink<Integer, CompletionStage<Done>> printSink =
Sink.foreach(x -> {
if (x == 4) {
throw new Exception("Error Occurred");
}
System.out.println("Sink: " + x);
});
final RunnableGraph<CompletionStage<Done>> runnableGraph =
integerSource.toMat(printSink, Keep.right());
final RunnableGraph<CompletionStage<Done>> withResumingSupervision =
runnableGraph.withAttributes(ActorAttributes.withSupervisionStrategy(decider));
final CompletionStage<Done> result = withResumingSupervision.run(system);
您还可以针对不同类型的异常定义不同的监管策略:
final Function<Throwable, Supervision.Directive> decider =
exc -> {
if (exc instanceof MySpecificException) return Supervision.resume();
else return Supervision.stop();
};
如何从 Akka Streams 的 Sink 抛出的异常中恢复?
简单示例:
Source<Integer, NotUsed> integerSource = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
integerSource.runWith(Sink.foreach(x -> {
if (x == 4) {
throw new Exception("Error Occurred");
}
System.out.println("Sink: " + x);
}), system);
输出:
Sink: 1
Sink: 2
Sink: 3
如何处理异常并从源转到下一个元素? (又名 5、6、7、8、9)
默认情况下,supervision strategy 在抛出异常时停止流。要更改监管策略以删除导致异常的消息并继续处理下一条消息,请使用 "resume" 策略。例如:
final Function<Throwable, Supervision.Directive> decider =
exc -> {
return Supervision.resume();
};
final Sink<Integer, CompletionStage<Done>> printSink =
Sink.foreach(x -> {
if (x == 4) {
throw new Exception("Error Occurred");
}
System.out.println("Sink: " + x);
});
final RunnableGraph<CompletionStage<Done>> runnableGraph =
integerSource.toMat(printSink, Keep.right());
final RunnableGraph<CompletionStage<Done>> withResumingSupervision =
runnableGraph.withAttributes(ActorAttributes.withSupervisionStrategy(decider));
final CompletionStage<Done> result = withResumingSupervision.run(system);
您还可以针对不同类型的异常定义不同的监管策略:
final Function<Throwable, Supervision.Directive> decider =
exc -> {
if (exc instanceof MySpecificException) return Supervision.resume();
else return Supervision.stop();
};