# Akka streams exception handling

**URL:** <https://discuss.akka.io/t/akka-streams-exception-handling/6557>\
**Category:** Akka Libraries\
**Created:** [May 22, 2020, 1:59pm UTC](https://discuss.akka.io/t/akka-streams-exception-handling/6557 "2020-05-22T13:59:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![flo](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.akka.io/flo/32/1878_2.png) [@flo](https://discuss.akka.io/u/flo)\
**Post date:** [May 22, 2020, 1:59pm UTC](https://discuss.akka.io/t/akka-streams-exception-handling/6557/1 "2020-05-22T13:59:28Z")

</div>

Hi,

What is the right way to handle exceptions in akka streams? Closing the stream and retrying is not an option as the failure happens due to invalid properties of the stream element: the exception would just occur again upon retry. Instead I would like to send the failing element to some separate sink in order to make the issue visible to the end-users and continue with the next element / keep the stream running.

My concern with what is described in [https://doc.akka.io/docs/akka/current/stream/stream-error.html](https://doc.akka.io/docs/akka/current/stream/stream-error.html) is that i do not get hold of the faulty element upon the exception. Which means in most cases i cannot output element specific information (e.g. element ID) to the end-user.

Thanks.

---

<div class="post-metadata">

**Author:** ![pbernet](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.akka.io/pbernet/32/370_2.png) [@pbernet](https://discuss.akka.io/u/pbernet)\
**Post date:** [May 22, 2020, 3:49pm UTC](https://discuss.akka.io/t/akka-streams-exception-handling/6557/2 "2020-05-22T15:49:22Z")

</div>

Hi,

Errors due to "invalid properties of the stream element” may be handled by treating these errors as data, which means passing the invalid elements downstream and divert them to an appropriate sink.

```auto
val flow: Flow[Int, Either[Valid[Int], Invalid[Int]], NotUsed] = Flow[Int]
  .map { x =>
    if (x % 2 == 0) Left(Valid(x))
    else Right(Invalid(x, Some(new Exception("Is odd"))))
  }
  .map {
    case left@Left(_) => businessLogicOn(left)
    case right@Right(_) => right
  }
  ...
  //Divert invalid elements
  .divertTo(errorSink.contramap(_.right.get), _.isRight)

```

This concept is explained (among others) in this inspiring talk by Colin Breck:

> **[Patterns for Streaming Telemetry with Akka Streams - @scaladays](https://www.scaladays.org/2018/new-york/schedule/patterns-for-streaming-telemetry-with-akka-streams)**
>
> Thursday June 21st, 13:15-14:00 - Foundations

A complete sample is here:

> <https://github.com/pbernet/akka_streams_tutorial/blob/master/src/main/scala/sample/stream_divert/DivertTo.scala>

Hope that helps  
Paul
