<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Poorva Gokhale on Medium]]></title>
        <description><![CDATA[Stories by Poorva Gokhale on Medium]]></description>
        <link>https://medium.com/@poorvasgokhale?source=rss-250a5377c43a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CF3j4vFdpIXmtJ9x</url>
            <title>Stories by Poorva Gokhale on Medium</title>
            <link>https://medium.com/@poorvasgokhale?source=rss-250a5377c43a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 12:08:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@poorvasgokhale/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Error handling with Scala Futures]]></title>
            <link>https://levelup.gitconnected.com/error-handling-with-scala-futures-2730a44cbeb4?source=rss-250a5377c43a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2730a44cbeb4</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Poorva Gokhale]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 12:52:08 GMT</pubDate>
            <atom:updated>2020-04-24T12:00:58.829Z</atom:updated>
            <content:encoded><![CDATA[<p>There are different ways of handling asynchronous errors in Scala. Often it’s confusing to decide right way. After trying out multiple approaches, I have formed an understanding and I will be sharing my learnings here. In error handling context, it is very important whether you are writing an application or a library. In this blog post, I am comparing different ways of error handling from application writer and library author’s perspective.</p><blockquote>For quick read, you can just go through <strong>Inshorts </strong>section.</blockquote><p>Let’s get started.</p><h3>Different ways of error handling</h3><h4>Exceptions</h4><p>API return type capture only success value (which can be ADT). Errors that can occur in API call are essentially Exceptions. For example,</p><pre><em>/**<br> * Reads Student data for given Id from database.<br> * </em><strong>@return </strong><em>a future which completes with the Student data if found for given studentId.<br> *         It can fail with </em><strong><em>InvalidIdException</em></strong><em> or    </em><strong><em>DatabaseConnectionException</em></strong><em><br> */<br></em><strong>def </strong>getStudentData(studentId: String): Future[Student]</pre><pre><em>/**<br> * search hobby clubs in provided city matching provided interest area<br> *<br> * </em><strong>@return </strong><em>future which completes with the Set of hobby clubs matching interest areas in provided city.<br> *         It can fail with </em><strong><em>FacilityDoesNotExistForCityException</em></strong><em> or </em><strong><em>NoMatchingHobbyClubException</em></strong><em> <br> */<br></em><strong>def </strong>searchHobbyClubs(city: City, interestArea: Interest): Future[Set[HobbyClub]]</pre><p><strong>Consuming exception based API</strong></p><p><strong>Unlike Java, all exceptions in Scala are unchecked</strong>. We need to write a partial function in order to catch one explicitly. It is important to make sure that we are catching what we want to catch. For example,</p><pre>// example code<br>getStudentData(studentId)<br> .recover {<br>    case <em>InvalidIdException</em><strong><em> =&gt; // </em></strong><em>handle specific exception<br>    case NonFatal(_) =&gt; // catch all for all non fatal exception<br> }</em></pre><p><strong>Composition</strong></p><p>Layers which are composing on top of these API will have signature <strong><em>Future[T] → Future[S]</em></strong><em> </em>where T and S both carry errors as Exceptions.<em> </em>For example, following API composes</p><p><em>Future[Student] → Future[Set[HobbyClub]]</em></p><pre><strong>// </strong>This API can fail with <strong><em>InvalidIdException </em></strong><em>or</em><strong><em> DatabaseConnectionException </em></strong><em>or</em><strong><em> FacilityDoesNotExistForCityException<br></em></strong><em>or</em><strong><em> NoMatchingHobbyClubException</em></strong></pre><pre><strong>def</strong> suggestHobbyClubFor(studentId: String): Future[Set[HobbyClub]] = {<br>  getStudentData(studentId)<br>    .map(student =&gt; searchHobbyClasses(student.city, student.interest))<br>}</pre><p>Composing these APIs is pretty straightforward. Advantage of this approach is simpler return types. One can work on success values with ease.</p><p><strong>Application</strong></p><p>You can choose Exceptions based approach in application provided you know which all exceptions that can occur at multiple layers and handle them appropriately using <strong><em>recover</em></strong> block.</p><p><strong>Library</strong></p><p>If you are writing library then you will have to document your APIs well and you should always keep your document up to date as consumer of this library will be relying heavily on documentation to see what all exceptions can occur.</p><blockquote><strong>Inshorts</strong></blockquote><blockquote>Return type capturing only success values simplifies API signature. Easy to compose.</blockquote><blockquote>Need to rely on documentation for errors (which can easily go out of date) or go through code each time you use API can be painful.</blockquote><h4>Algebraic Data Type (Flat Hierarchy for Success and Error)</h4><p>Unlike exception based approach, ADT approach treat <strong>errors as values</strong> and also captured in return type along with success values. For example,</p><pre><strong>sealed trait </strong>StudentData</pre><pre><strong>object </strong>StudentData {<br>  <strong>case class </strong>Success(student: Student) <strong>extends </strong>StudentData<br><br>  <strong>sealed trait </strong>Failure <strong>extends </strong>StudentData<br>  <strong>case object </strong>InvalidIdException <strong>extends </strong>Failure<br>  <strong>case class </strong>DatabaseConnectionException(reason: String) <strong>extends    </strong>Failure<br>}</pre><pre><strong>def </strong>getStudentData(studentId: String): Future[StudentData]</pre><p><strong>Consumptions</strong></p><pre>getStudentData(studentId)<br>  .map {<br>    <strong>case </strong><em>Success</em>(student)   =&gt;<br>    <strong>case </strong>InvalidIdException =&gt;<br>    <strong>case </strong>DatabaseConnectionException(e) =&gt; <br>  }</pre><p>Here you will get <strong>all benefits of ADT</strong> like <strong>pattern matching</strong> and <strong>compiler help </strong>like<strong> </strong>warning incase you forget to handle something.</p><p>Most of the times, domain need to just to work on success values. So you will need some mechanism to identify which response is success and which is failure. So you will need <strong>marker traits for success and failure </strong>like I have used <em>Failure </em>marker trait in above example. For example,</p><pre>getStudentData(studentId)<br>  .map {<br>    <strong>case </strong>StudentData.<em>Success</em>(student)   =&gt;<br>    <strong>case </strong><em>failure</em>: StudendData.Failure =&gt;<br>  }</pre><p><strong>Composition</strong></p><p>Layers consuming these APIs will have their own ADT for response. This ADT will need to consider errors from downstream APIs as well. For example,</p><p><em>Future[T] → Future[S]</em> where T and S are different ADTs. S will have to accommodate T.failure values. Like in following example <em>FetchStudentDataError </em>accommodate failure from <em>getStudentData</em></p><pre><strong>sealed trait </strong>HobbyClubResponse<br><br><strong>case class </strong>Success(hobbyClubs: Set[String]) <strong>extends </strong>HobbyClubResponse</pre><pre><strong>sealed trait </strong>Failure <strong>extends </strong>HobbyClubResponse<br><strong>case object </strong>FacilityDoesNotExistForCity <strong>extends </strong>Failure<br><strong>case object </strong>NoMatchingHobbyClub <strong>extends </strong>Failure<br><strong>case class </strong>FetchStudentDataError(error: StudentData.Failure) <strong>extends </strong>Failure</pre><p><strong><em>As we go on composing on top of these APIs, response ADT can really become convoluted.</em></strong></p><p><strong>Application</strong></p><p>Many times your computations are success biased. In such cases, pattern matching on flat response ADT and then working on success values can be painful. You can write generic abstraction which are success biased but it needs some convention to be followed all over codebase to identify success and error values like marker traits for success in failure in above examples.</p><p><strong>Library</strong></p><p>All concerns mentioned for application are applicable here. Advantage that you get here is return type having <strong>flat ADT</strong> (containing success and error values) is <strong>best for consumers of library</strong>. This way consumers get all benefits of static typing with response as ADT. Consumers can choose to deal with both success and error values or deal with only success responses and ignore all error responses. In summary, all possible ways of error handling are open for consumers of library.</p><blockquote><strong>Inshorts</strong></blockquote><blockquote>Capturing error values as type is great help. By looking at response type you know all possible success and error cases.</blockquote><blockquote>Composing APIs with success and error types in one ADT can turn out tricky and it might result in convoluted response hierarchy.</blockquote><blockquote>Some mechanism to identify success and failure values (like marker traits). Generic abstraction for success biased or error biased computation can be written to make composing easier.</blockquote><h4>Either</h4><p><em>Either </em>is a way to represent possible values either left or right . <em>Either[L, R]</em> where L (left) is used for error ADT and R(right) is used for success ADT. For Example,</p><pre><strong><br></strong>// success value<strong><br>case class </strong>StudentData(student: Student)</pre><pre>// error ADT<br><strong>sealed trait </strong>StudentDataError<br><strong>case object </strong>InvalidIdException  <strong>extends </strong>StudentDataError<br><strong>case class </strong>DatabaseConnectionException(reason: String) <strong>extends </strong>StudentDataError</pre><pre>//API<br><strong>def </strong>getStudentData(studentId: String): Future[Either[StudentDataError,StudentData]]</pre><p><strong><em>Either[L,R] was not designed for error handling, but as Either is right biased it is widely used for error handling where error values are at left and success values at right. </em></strong>Try is special case of Either where L is Throwable (Exception) and R is success.</p><p><strong>Consumption</strong></p><pre>getStudentData(studentId)<br>  .map {<br>    <strong>case </strong>Left(error)   =&gt; // do something with error<br>    <strong>case </strong>Right(value)<strong>  </strong>=&gt; // compute on success<br>  }</pre><p>Here you will <strong>get all benefits for static typing</strong>, <strong>compiler help</strong> as like in previous flat ADT approach. In addition to this, if you want to compute on success values you can use <strong>combinators like map, flatMap</strong> etc. from Scala standard library. As opposed to flat ADT approach, you <strong>don’t need to write abstractions for success biased</strong> computation. If you want to <strong>compose error values</strong>, you can use <strong><em>left</em></strong><em> </em>from Scala standard library.</p><p><strong>Composition</strong></p><p>Composing on these APIs will result in <strong>Future[Either[L, R]] → Future[Either[T, S]]. </strong>Composing this way is also very straightforward. For example,</p><pre><br><strong>case class </strong>HobbyClubResponse(hobbyClubs: Set[String])</pre><pre><strong>sealed trait</strong> HobbyClubError<br><strong>case object </strong>FacilityDoesNotExistForCity <strong>extends </strong>HobbyClubError<br><strong>case object </strong>NoMatchingHobbyClub <strong>extends </strong>HobbyClubError<br><strong>case class </strong>FetchStudentDataError(error: StudentData.Failure) <strong>extends </strong>HobbyClubError</pre><pre>getStudentData(studentId)<br>  .map {<br>    <strong>case </strong>Left(error) =&gt; <em>Left</em>(<em>FetchStudentDataError</em>(error))<br>    <strong>case </strong>Right(studentData) =&gt; searchHobbyClasses(student.city, student.interest))<br>  }</pre><p>If you want to compute only on success values and carry error as it is, you can use map like</p><pre>getStudentData(studentId)<br>  .map(_.map(student =&gt; searchHobbyClasses(student.city, student.interest)))</pre><p><strong>Application &amp; Library</strong></p><p>In my opinion, this is very attractive way of error handling for writing an Application or Library. You get most benefits. In case of library, you can choose to convert Either into flat response ADT for public facing APIs. This way you will get all benefits of Either approach and won’t force consumers to work with Either.</p><blockquote><strong>Inshorts</strong></blockquote><blockquote>You get most benefits like static typing for success and error. Success and Error both are separate ADTs so they are not complex as compared to flat ADT approach. Computation on success and error are easy with combinators like map, flatMap, left etc.</blockquote><blockquote>However you can write small utility methods so you don’t need to go in nested maps and composing can be made yet more simpler. like following</blockquote><pre><strong>def </strong>right[S](f: R =&gt; S)(<strong>implicit </strong>executor: ExecutionContext): Future[Either[L, S]] = futureEither.map(_.map(f))<br><br><strong>def </strong>left(<strong>implicit </strong>executor: ExecutionContext): Future[<em>Either</em>.LeftProjection[L, R]] = futureEither.map(_.left)<br><br><strong>def </strong>flatRight[S](f: R =&gt; Future[Either[L, S]])(<strong>implicit </strong>executor: ExecutionContext): Future[Either[L, S]] =<br>  futureEither.flatMap {<br>    <strong>case </strong>Left(l)  =&gt; Future.<em>successful</em>(<em>Left</em>(l))<br>    <strong>case </strong>Right(r) =&gt; f(r)<br>  }</pre><h3><strong>Conclusion</strong></h3><p>Given we are in Scala world, treating errors are values and getting all benefits of static typing is should be first choice. In my opinion, using Either approach and converting it into flat ADT at public facing layer is best as you get all benefits of Either within your application or library and consumers are not forced to work with Either.</p><p>One should keep following things in mind before deciding error handling approach:</p><p><strong>Use cases where error drive which path to follow in code</strong></p><p>In case of application, capturing error as response type (as flat ADT or Either) makes sense when you have use cases where you decide what to do based on error. For library I would recommend capturing error as values.</p><p><strong>Simplicity &amp; Maintainability of code</strong></p><p>There is a cost when you choose flat ADT or Either over Exceptions. Response hierarchy do get complicated as compared to Exception. But you get other benefits of treating error as values. There is a trade off. So choose approach that suit’s better.</p><p>That’s all!!!</p><p>Do let me know if you have any feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2730a44cbeb4" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/error-handling-with-scala-futures-2730a44cbeb4">Error handling with Scala Futures</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>