recover
Allow sending of one last element downstream when a failure has happened upstream.
Signature
Source.recover
Source.recover
Flow.recover
Flow.recover
Description
recover
allows you to emit a final element and then complete the stream on an upstream failure. Deciding which exceptions should be recovered is done through a PartialFunction
. If an exception does not have a matching case match defined the stream is failed.
Recovering can be useful if you want to gracefully complete a stream on failure while letting downstream know that there was a failure.
Throwing an exception inside recover
will be logged on ERROR level automatically.
Reactive Streams semantics
emits when the element is available from the upstream or upstream is failed and pf returns an element
backpressures when downstream backpressures, not when failure happened
completes when upstream completes or upstream failed with exception pf can handle
Below example demonstrates how recover
gracefully complete a stream on failure.
- Scala
-
source
Source(0 to 6) .map(n => // assuming `4` and `5` are unexpected values that could throw exception if (List(4, 5).contains(n)) throw new RuntimeException(s"Boom! Bad value found: $n") else n.toString) .recover { case e: RuntimeException => e.getMessage } .runForeach(println)
- Java
-
source
Source.from(Arrays.asList(0, 1, 2, 3, 4, 5, 6)) .map( n -> { // assuming `4` and `5` are unexpected values that could throw exception if (Arrays.asList(4, 5).contains(n)) throw new RuntimeException(String.format("Boom! Bad value found: %s", n)); else return n.toString(); }) .recover( PFBuilder.<Throwable, String>create() .match(RuntimeException.class, Throwable::getMessage) .build()) .runForeach(System.out::println, system);
This will output:
- Scala
-
source
0 1 2 3 // last element before failure Boom! Bad value found: 4 // first element on failure
- Java
-
source
0 1 2 3 // last element before failure Boom! Bad value found: 4 // first element on failure
The output in the line before failure
denotes the last successful element available from the upstream, and the output in the line on failure
denotes the element returns by partial function when upstream is failed.