mapError
While similar to recover
this operators can be used to transform an error signal to a different one without logging it as an error in the process.
Signature
Source.mapError
Source.mapError
Flow.mapError
Flow.mapError
Description
While similar to recover
this operators can be used to transform an error signal to a different one without logging it as an error in the process. So in that sense it is NOT exactly equivalent to recover(t => throw t2)
since recover would log the t2
error.
Since the underlying failure signal onError arrives out-of-band, it might jump over existing elements. This operators can recover the failure signal, but not the skipped elements, which will be dropped.
Similarly to recover
throwing an exception inside mapError
will be logged on ERROR level automatically.
Example
The following example demonstrates a stream which throws ArithmeticException
when the element 0
goes through the map
operator. ThemapError
is used to transform this exception to UnsupportedOperationException
.
- Scala
-
source
Source(-1 to 1) .map(1 / _) .mapError { case _: ArithmeticException => new UnsupportedOperationException("Divide by Zero Operation is not supported.") with NoStackTrace } .runWith(Sink.seq) .onComplete { case Success(value) => println(value.mkString) case Failure(ex) => println(ex.getMessage) } // prints "Divide by Zero Operation is not supported."
- Java
-
source
final ActorSystem system = ActorSystem.create("mapError-operator-example"); Source.from(Arrays.asList(-1, 0, 1)) .map(x -> 1 / x) .mapError( ArithmeticException.class, (ArithmeticException e) -> new UnsupportedOperationException("Divide by Zero Operation is not supported.")) .runWith(Sink.seq(), system) .whenComplete( (result, exception) -> { if (result != null) System.out.println(result.toString()); else System.out.println(exception.getMessage()); }); // prints "Divide by Zero Operation is not supported."
Reactive Streams semantics
emits when element is available from the upstream or upstream is failed and pf returns an element backpressures when downstream backpressures completes when upstream completes or upstream failed with exception pf can handle