<?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 Sunpreet Singh on Medium]]></title>
        <description><![CDATA[Stories by Sunpreet Singh on Medium]]></description>
        <link>https://medium.com/@sunpreet.?source=rss-4706a77557fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZE6K-eAZB0TO9H96.jpg</url>
            <title>Stories by Sunpreet Singh on Medium</title>
            <link>https://medium.com/@sunpreet.?source=rss-4706a77557fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:07:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sunpreet./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[I Stopped Catching DioException Everywhere in Flutter — Here’s What Replaced It]]></title>
            <link>https://medium.com/@sunpreet./i-stopped-catching-dioexception-everywhere-in-flutter-heres-what-replaced-it-38a30e66b11f?source=rss-4706a77557fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/38a30e66b11f</guid>
            <category><![CDATA[dios]]></category>
            <category><![CDATA[railway-dio]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[flutter-package]]></category>
            <dc:creator><![CDATA[Sunpreet Singh]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 02:38:48 GMT</pubDate>
            <atom:updated>2026-08-03T02:38:48.469Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve worked with dio in a Flutter app of any size, you&#39;ve probably already done the sensible thing: pulled the repeated try/catch into one shared base repository or a single helper function, instead of pasting it everywhere.</p><pre>try {<br>  final response = await dio.get(&#39;/something&#39;);<br>  return User.fromJson(response.data);<br>} on DioException catch (e) {<br>  if (e.type == DioExceptionType.connectionTimeout) {<br>    // handle timeout<br>  } else if (e.response?.statusCode == 401) {<br>    // handle unauthorized<br>  }<br>  // ...<br>}</pre><p>That helper solves duplication. It doesn’t solve two other things: nothing forces every call site to actually <em>handle</em> every failure case, and it’s specific to whatever client your team standardized on — if part of the app uses dio and another part uses chopper (common after a partial migration), you&#39;re maintaining two versions of the same helper with no shared contract between them.</p><p>I covered the pattern that fixes both of those — Railway Oriented Programming — in <a href="https://medium.com/@sunpreet./railway-oriented-programming-stop-writing-error-handling-spaghetti-cf3c7a6d2d3e">the first article of this series</a>, using chopper as the example client. This one is about the same idea applied to dio, with <a href="https://pub.dev/packages/railway_dio">railway_dio</a> — and, more usefully, about what a typed, composable version of &quot;the helper you&#39;d eventually build yourself&quot; actually gets you.</p><figure><img alt="with and without railway implementation" src="https://cdn-images-1.medium.com/max/1024/1*eEQB7MoA4sKcxN2rRuel2Q.png" /></figure><h3>Switching clients costs you nothing at the call site</h3><p>Both railway_chopper and railway_dio resolve every network call into the exact same shape: Either&lt;NetworkFailure, T&gt;. Same failure taxonomy too — network, timeout, unauthorized, clientError, server, unknown. Your repository or domain layer never needs to know or care which HTTP client sits underneath — it just handles Either&lt;NetworkFailure, T&gt; once, the same way, everywhere.</p><p>But look at how each package actually hands you that Either:</p><pre>// railway_chopper — wraps the call<br>final result = await mapResponse(() =&gt; myApi.getSomething());<br><br>// railway_dio — extends the future<br>final result = await dio.get(&#39;/users/1&#39;).toEither((data) =&gt; User.fromJson(data));</pre><p>That difference isn’t inconsistency — it’s forced by how each client reports failure. Chopper’s Response already carries structured success/failure information, so wrapping it is an inspection problem. Dio throws a DioException on failure instead of returning a response with an error flag, so wrapping it is an exception-classification problem: catch it, figure out whether it was a timeout, no connection, a 401, a 5xx, then build the matching NetworkFailure. Same destination, different route — exactly what you&#39;d expect from a contract that stays stable while respecting what each client actually does underneath.</p><h3>Typed backend errors, not just transport errors</h3><p>Most real backends don’t just return a bare 4xx or 5xx — they return a JSON error payload with a code, a message, maybe field-level errors. Without a way to decode that, you’re back to parsing errorBody by hand at the call site, right back in per-repository special-casing.</p><p>toEither takes a second, optional decoder for exactly this:</p><pre>final result = await dio.get&lt;Map&lt;String, dynamic&gt;&gt;(&#39;/users/1&#39;).toEither(<br>  (data) =&gt; User.fromJson(data),<br>  (errorJson) =&gt; ApiError.fromJson(errorJson),<br>);<br><br>result.match(<br>  (failure) {<br>    if (failure is NetworkClientFailure &amp;&amp; failure.errorBody is ApiError) {<br>      final apiError = failure.errorBody as ApiError;<br>      print(&#39;API Error Code: ${apiError.code}&#39;);<br>    }<br>  },<br>  (user) =&gt; print(&#39;Loaded User: ${user.name}&#39;),<br>);</pre><p>Now your structured backend error rides the failure track as a typed value, right alongside the transport-level classification — instead of forcing you to choose between “typed failure” and “the actual error the backend sent you.”</p><h3>One contract, two clients, on purpose</h3><p>The obvious question: if the contract’s identical, why not one universal package with a client adapter underneath? Because chopper and dio solve HTTP differently at the root — chopper leans on codegen and converters, dio leans on a plain client plus interceptors — and forcing one abstraction over both would leak one client’s assumptions into the other’s usage. Better to keep the <em>contract</em> — Either&lt;NetworkFailure, T&gt;, the same failure variants — identical, and let each package own its client&#39;s actual quirks. That&#39;s a design decision, not a shortcut: the same &quot;what&#39;s NOT in here&quot; boundary from railway_chopper (no auth interception, no DTOs, no domain failures, nothing feature-specific) applies just as strictly here. Same spec, two implementations.</p><h3>This generalizes — that’s the point</h3><p>This is part of what’s shaping up to be a <strong>Railway Suite</strong> — railway_chopper and railway_dio today, railway_http next for anyone on plain package:http. Same Either&lt;NetworkFailure, T&gt; contract across all three; pick whichever matches the client you&#39;re already using, and none of your feature code has to know or care which one is underneath.</p><p>Both packages are early — worth checking their pub.dev pages for current test coverage and CI status rather than taking my word for it. But the design intent isn’t a one-off wrapper: it’s one spec, applied consistently, with the boundaries documented rather than implied.</p><p>After railway_http, this series moves into a broader set of articles on design patterns generally — grounded in real Flutter/Dart examples, not tied to any one framework. Follow along if that&#39;s useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38a30e66b11f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Railway Oriented Programming: Stop Writing Error-Handling Spaghetti]]></title>
            <link>https://medium.com/@sunpreet./railway-oriented-programming-stop-writing-error-handling-spaghetti-cf3c7a6d2d3e?source=rss-4706a77557fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf3c7a6d2d3e</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[chopper]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Sunpreet Singh]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 19:05:13 GMT</pubDate>
            <atom:updated>2026-07-28T19:26:35.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0FpUB6EjHGeReiyjDrKbw.png" /></figure><p>If you’ve built anything that talks to a network, a database, or user input, you’ve written this code a hundred times:</p><pre>result1 = stepOne(input)<br>if result1 is error:<br>    return result1.error<br><br>result2 = stepTwo(result1.value)<br>if result2 is error:<br>    return result2.error<br><br>result3 = stepThree(result2.value)<br>if result3 is error:<br>    return result3.error<br><br>return result3.value</pre><p>Every step needs its own guard clause. Every guard clause looks the same. And the actual business logic — the part anyone cares about — is buried under repeated error-checking scaffolding. Add a fourth step and you add a fourth if. Nest a few of these and you get the classic &quot;error-handling pyramid.&quot;</p><p><strong>Railway Oriented Programming (ROP)</strong> is a way to write this same logic without the repetition, and without losing any type safety along the way. The term comes from F# developer Scott Wlaschin, who described it with a genuinely useful metaphor — <strong>“Two tracks, one switch”</strong></p><figure><img alt="ROP Two Track Model" src="https://cdn-images-1.medium.com/max/1024/1*8MyCFiDY6YUZ6cnRSyQ-zQ.png" /></figure><p>Picture a railway with two parallel tracks: a <strong>success track</strong> and a <strong>failure track</strong>. A request enters on the success track. Each processing step is a switch: if the step succeeds, the train continues on the success track into the next step; if it fails, the train is diverted onto the failure track — and it stays there. Every later switch is skipped automatically, because there’s nothing left to divert. The train rides the failure track straight through to the end, carrying whatever error caused the detour.</p><p>That’s the whole idea. You stop asking “did this fail?” after every step, because failure isn’t a special case you check for — it’s a track the data is already on or isn’t. The composition itself handles the branching.</p><h3>The type that makes this possible</h3><blockquote>To build railway tracks in code, you need a type that can hold <em>either</em> a success value <em>or</em> a failure value, never both, and you need a way to chain operations over it that automatically respects which track you’re on.</blockquote><p>In functional programming this type usually has one of two names:</p><ul><li>Result&lt;T, E&gt; — a result that&#39;s either Ok(T) or Err(E)</li><li>Either&lt;L, R&gt; — a value that&#39;s either Left(L) (conventionally the failure) or Right(R) (conventionally the success — &quot;right&quot; as in &quot;correct&quot;)</li></ul><p>Whatever it’s called, the mechanics are the same. You get a map operation that transforms the success value and leaves a failure untouched, and a bind/flatMap operation that lets you chain a function which itself might fail. Written in pseudocode, the pyramid from earlier collapses into this:</p><pre>stepOne(input)<br>  .bind(stepTwo)<br>  .bind(stepThree)<br>  .match(<br>    onFailure: handleError,<br>    onSuccess: useValue<br>  )</pre><p>No intermediate if. No repeated error branches. If stepOne fails, stepTwo and stepThree never even run — the failure just rides through. You handle it exactly once, at the end. This is the part that&#39;s genuinely language-agnostic: Rust has Result, Kotlin has Result and libraries with Either, TypeScript has fp-ts&#39;s Either, Swift has Result, Java has similar constructs via libraries. The pattern doesn&#39;t care what language hosts it.</p><h3>Bringing it into Dart</h3><p>Dart doesn’t ship a Result/Either type in its standard library, but <a href="https://pub.dev/packages/fpdart">fpdart</a> provides one, and it composes cleanly with Dart&#39;s type system. I built <a href="https://pub.dev/packages/railway_chopper">railway_chopper</a> to apply exactly this pattern at a spot where Flutter apps accumulate the most error-handling noise: the network layer, using the <a href="https://pub.dev/packages/chopper">chopper</a> HTTP client.</p><p>The package does two small things. It builds a configured ChopperClient, and it wraps any chopper request so it resolves into a single Either&lt;NetworkFailure, T&gt; instead of a raw Response you have to inspect manually:</p><pre>final client = buildChopperClient(<br>  baseUrl: &#39;https://api.example.com&#39;,<br>);<br><br>final result = await mapResponse(<br>  () =&gt; client.get&lt;Map&lt;String, dynamic&gt;, Map&lt;String, dynamic&gt;&gt;(<br>    Uri.parse(&#39;/todos/1&#39;),<br>  ),<br>);<br><br>result.match(<br>  (failure) =&gt; print(&#39;Request failed: $failure&#39;),<br>  (todo) =&gt; print(&#39;Todo #${todo[&#39;id&#39;]}: ${todo[&#39;title&#39;]}&#39;),<br>);</pre><p>NetworkFailure is a sealed union covering the ways a transport call actually fails — network, timeout, server, clientError, unauthorized, unknown — so the compiler forces you to account for failure as a real, typed value instead of an exception that might surface three layers away. There&#39;s no try/catch visible to the caller, no null check, and no separate code path for &quot;what if this one call breaks.&quot; The success and failure paths are both just... values, and match is the single place you decide what to do with either one.</p><h3>Why bother?</h3><p>The benefit isn’t that ROP eliminates error handling — you still write the code that reacts to a failure. What it eliminates is the <em>repetition</em> of error handling, and the risk that comes with it: a forgotten null check, a swallowed exception, an early return someone missed when they added a fourth step. Chains built this way are also easier to test, since each step is a pure function you can call in isolation, and easier to extend, since adding a step means adding one more .bind, not restructuring a nested conditional.</p><p>It’s not free, and it’s not always the right tool. There’s a real learning curve if your team hasn’t worked with Result/Either before, and forcing every function in a codebase through this shape can be overkill for simple, low-risk operations. Where it pays off most is at layer boundaries — network calls, database queries, form validation, parsing — anywhere a chain of steps can each independently fail and you&#39;d otherwise be checking for that after every single one.</p><p>This is the first article in a short series on Railway Oriented Programming in Flutter/Dart. Next up: railway_dio and railway_http, applying the same pattern to different HTTP clients, so you can compare how the underlying idea stays identical even as the transport layer changes. After that, I&#39;m starting a broader series on design patterns generally — what problem each one actually solves, when it&#39;s worth reaching for, and where it falls apart — explained in a way that isn&#39;t tied to any one language or framework, but grounded in real Flutter/Dart examples throughout. Follow along if that&#39;s useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf3c7a6d2d3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>