<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>handling &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/handling/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Fri, 03 Nov 2017 22:59:46 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://jessewarden.com/wp-content/uploads/2016/08/cropped-Lambda2-32x32.png</url>
	<title>handling &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Error Handling Strategies</title>
		<link>https://jessewarden.com/2017/11/error-handling-strategies.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Wed, 01 Nov 2017 23:35:42 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[akka]]></category>
		<category><![CDATA[elixir]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[exception]]></category>
		<category><![CDATA[go]]></category>
		<category><![CDATA[handling]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[throw]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5373</guid>

					<description><![CDATA[Introduction There are various ways of handling errors in programming. This includes not handling it. Many languages have created more modern ways of error handling. An error is when the program, intentionally, but mostly not, breaks. Below, I&#8217;ll cover the 4 main ones I know: try/catch, explicit returns, either, and supervising crashes. We&#8217;ll compare various [&#8230;]]]></description>
										<content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>There are various ways of handling errors in programming. This includes not handling it. Many languages have created more modern ways of error handling. An error is when the program, intentionally, but mostly not, breaks. Below, I&#8217;ll cover the 4 main ones I know: try/catch, explicit returns, either, and supervising crashes. We&#8217;ll compare various languages on how they approach errors: Python, JavaScript, Lua, Go, Scala, Akka, and Elixir. Once you understand how the newer ways work, hopefully this will encourage you to abandon using potentially program crashing errors via the dated <code>throw</code>/<code>raise</code> in your programs.<br />
<span id="more-5373"></span></p>
<h2>Contents</h2>
<ul>
<li><a href="#whyevencare">Why Even Care</a></li>
<li><a href="#throwtrycatch">Throw, Try, Catch, Finally</a></li>
<li><a href="#explicitreturn">Explicit Return</a>
<ul>
<li><a href="#variouslanguageexamples">Various Language Examples of Explicit Returns</a></li>
<li><a href="#effectsoncoding">Effects On Coding</a></li>
<li><a href="#consonexplicitreturns">Cons on Explicit Returns</a></li>
</ul>
</li>
<li><a href="#either">Either, Left or Right, and Pattern Matching</a>
<ul>
<li><a href="#eithertype">The Either Type</a></li>
<li><a href="#eitherexamples">Either Examples</a></li>
<li><a href="#patternmatching">Pattern Matching</a></li>
</ul>
</li>
<li><a href="#letitcrash">Let It Crash</a></li>
<li><a href="#conclusions">Conclusions</a></li>
</ul>
<p><a name="whyevencare"></a></p>
<h1>Why Even Care?</h1>
<p>When programs crash, log/print/trace statements and errors aren&#8217;t always helpful to quickly know what went wrong. Logs, if there are at all, tell a story you have to decipher. Errors, if there, sometimes give you a long stack trace, which often isn&#8217;t long enough. Asynchronous code can make this harder. Worse, both are often completely unrelated to the root cause, or lie and point you in the completely wrong debugging direction. Overall, most crashes aren&#8217;t always helpful in debugging why your code broke.</p>
<p>Various error handling strategies can prevent these problems.<br />
<a name="throwtrycatch"></a></p>
<h1 id="throw-try-catch-finally">Throw, Try, Catch, Finally</h1>
<p>The original way to implement an error handling strategy is to throw your own errors.</p>
<pre><code class="lang-javascript">// a type example
validNumber = n =&gt; _.isNumber(n) &amp;&amp; _.isNaN(n) === false;
add = (a, b) =&gt; {
   if(validNumber(a) === false) {
     throw new Error(`a is an invalid number, you sent: ${a}`);
   }
   if(validNumber(b) === false) {
     throw new Error(`b is an invalid number, you sent: ${b}`);
   }
   return a + b;
};
add('cow', new Date()); // throws
</code></pre>
<p>They have helpful and negative effects that take pages of text to explain. The reason you shouldn&#8217;t use them is they can crash your program. While often this is often intentional by the developer, you could negatively affect things outside your code base like a user&#8217;s data, logs, and this often trickles down to user experience. It also makes it more difficult for the developer debugging to pinpoint exactly where it failed and why.</p>
<p>I jokingly call them explosions because they accidentally can affect completely unrelated parts of the code when they go off. Compilers and runtime errors in sync and async code still haven&#8217;t gotten good enough (except maybe <a href="http://elm-lang.org/">Elm</a>) to help us immediately diagnose what we, or someone else, did wrong.</p>
<p>We don&#8217;t want to crash a piece of code or entire programs.</p>
<p>We want to correctly identify what went wrong, give enough information for the developer to debug and/or react, and ensure that error is testable. Intentional developer throws attempt to tell you what went wrong and where, but they don&#8217;t play nice together, often mask the real issue in cascading failures, and while sometimes testable in isolation, they are harder to test in larger composed programs.<br />
<a name="explicitreturn"></a></p>
<h1 id="explicit-return">Explicit Return</h1>
<p>The second option is what Go, Lua, and sometimes Elixir do, where you handle the possible error on a per function basis. They return information if the function worked or not along with the regular return value. Basically they return 2 values instead of 1. These are different for asynchronous calls per language so let&#8217;s focus on synchronous for now.</p>
<p><a name="variouslanguageexamples"></a></p>
<h2 id="various-langauge-examples-of-explicit-returns">Various Language Examples of Explicit Returns</h2>
<p>Lua functions will throw errors just like Python and JavaScript. However, using a function called protected call, <code class="lang-lua">pcall</code> it will capture the exception as part of a 2nd return value:</p>
<pre><code class="lang-lua">function datBoom()
  error({reason='kapow'})
end
ok, error = pcall(datBoom)
print("did it work?", ok, "error reason:", error.reason)
-- did it work? false, error: kapow
</code></pre>
<p>Go has this functionality natively built in:</p>
<pre><code class="lang-go">func datBoom() (err error)
ok, err := datBoom()
if err != nil {
  log.Fatal(err)
}
</code></pre>
<p>&#8230; and so does Elixir (with the ability to opt out using a ! at the end of a function invocation):</p>
<pre><code class="lang-elixir">def datBoom do
  {:error, "kapow"}
end

{:error, reason} = datBoom()
IO.puts "Error: #{reason}" ## kapow
</code></pre>
<p>While Python and JavaScript do not have these capabilities built into the language, you can easily add them.</p>
<p>Python can do the same using tuples:</p>
<pre><code class="lang-python">def datBoom():
  return (False, 'kapow')

ok, error = datBoom()
print("ok:", ok, "error:", error) # ('ok:', False, 'error:', 'kapow')
</code></pre>
<p>JavaScript can do the same using Object destructuring:</p>
<pre><code class="lang-javascript">const datBoom = () =&gt; ({ok: false, error: 'kapow'});
const {ok, error} = datBoom();
console.log("ok:", ok, "error:", error); // ok: false error: kapow
</code></pre>
<p><a name="effectsoncoding"></a></p>
<h2 id="effects-on-coding">Effects On Coding</h2>
<p>This causes a couple of interesting things to happen. First, developers are forced to handle errors when and where they occur. In the throw scenario, you run a lot of code, and sprinkle throws where you think it&#8217;ll break. Here, even if the functions aren&#8217;t pure, every single one could possibly fail. There is no point continuing to the next line of code because you already failed at the point of running the function and seeing it failed (<code>ok</code> is false) an error was returned telling you why. You start to really think how to architect things differently.</p>
<p>Second, you know WHERE the error occurred (mostly). The &#8220;why&#8221; is still always up for debate.</p>
<p>Third, and most important, if the functions are pure, they become easier to unit test. Instead of &#8220;I get my data, else it possibly blows up&#8221;, it immediately tells you: &#8220;I worked, and here&#8217;s your data&#8221;, or &#8220;I broke, and here&#8217;s what could be why&#8221;.</p>
<p>Fourth, these errors DO NOT (in most cases if your functions are pure) negatively affect the rest of the application. Instead of a throw which could take other functions down with it, you&#8217;re not throwing, you&#8217;re simply returning a different value from a function call. The function &#8220;worked&#8221; and reported its &#8220;results&#8221;. You&#8217;re not crashing applications just because a function didn&#8217;t work.</p>
<p><a name="consonexplicitreturns"></a></p>
<h2 id="cons-on-explicit-returns">Cons on Explicit Returns</h2>
<p>Excluding language specifics (i.e. Go panics, JavaScript&#8217;s async/await), you have to look in 2 to 3 places to see what went wrong. It&#8217;s one of the arguments against Node callbacks. People say not to use <code>throw</code> for control flow, yet all of you done is create a dependable <code>ok</code> variable. A positive step for sure, but still not a hugely helpful leap. Errors, if detected to be there, mold your code&#8217;s flow.</p>
<p>For example, let&#8217;s attempt to parse some JSON in JavaScript. You&#8217;ll see the absence of a <code>try/catch</code> replaced with an <code>if(ok === false)</code>:</p>
<pre><code class="lang-javascript">const parseJSON = string =&gt; {
  try {
    const data = JSON.parse(string);
    return {ok: true, data};
  } catch(error) {
    return {ok: false, error};
  }
};
const {ok, error, data} = parseJSON(new Date());
if(ok === false) {
  console.log("failed:", error);
} else {
  console.log("worked:", data);
}
</code></pre>
<p><a name="either"></a></p>
<h1 id="either-left-or-right-and-pattern-matching">Either, Left or Right, and Pattern Matching</h1>
<p><a name="eithertype"></a></p>
<h2 id="the-either-type">The Either Type</h2>
<p>Functions that can return 2 types of values are solved in functional programming by using the <code>Either</code> type, aka a disjoint union. <a href="https://www.typescriptlang.org/">Typescript</a> (strongly typed language &amp; compiler for JavaScript) supports a <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html">psuedo Either</a> as an <a href="https://leanpub.com/purescript/read#leanpub-auto-algebraic-data-types">Algebraic Data Type</a> (aka ADT).</p>
<p>For example, this TypeScript <code>getPerson</code> function will return <code>Error</code> or <code>Person</code> and your compiler helps you with that:</p>
<pre><code class="lang-typescript">// Notice TypeScript allows you to say 2 possible return values
function getPerson() : Error | Person
</code></pre>
<p>The <code>getPerson</code> will return either <code>Error</code>, or <code>Person</code>, but never both.</p>
<p>However, we&#8217;ll assume, regardless of language, you&#8217;re concerned with runtime, not compile time. You could be an API developer dealing with JSON from some unknown source, or a front end engineer dealing with user input. In functional programming they have the concept of a &#8220;left or right&#8221; in an Either type, or an object depending on your language of choice.</p>
<p>The convention is &#8220;Right is Correct&#8221; and &#8220;Left is Incorrect&#8221; (Right is right, Left is wrong).</p>
<p>Many languages already support this in one form or another:</p>
<p>JavaScript through Promises as values: <code>.then</code> is right, <code>.catch</code> is left) and Python via deferred values via the <a href="https://twistedmatrix.com/documents/16.5.0/core/howto/defer.html">Twisted</a> networking engine: <code>addCallback</code> is right, <code>addErrback</code> is left.</p>
<p><a name="eitherexamples"></a></p>
<h2 id="either-examples">Either Examples</h2>
<p>You can do this using a class or object in Python and JavaScript. We&#8217;ve already shown you the Object version above using <code>{ok: true, data}</code> for the right, and <code>{ok: false, error}</code> for the left.</p>
<p>Here&#8217;s a JavaScript Object Oriented example:</p>
<pre><code class="lang-javascript">class Either {
  constructor(right=undefined, left=undefined) {
    this._right = right;
    this._left = left;
  }
  isLeft() {
    return this.left !== undefined;
  }
  isRight() {
    return this.right !== undefined;
  }
  get left() {
    return this._left;
  }
  get right() {
    return this._right;
  }
}

const datBoom = () =&gt; new Either(undefined, new Error('kapow'));
const result = datBoom();
if(result.isLeft()) {
  console.log("error:", result.left);
} else {
  console.log("data:", result.right);
}
</code></pre>
<p>&#8230; but you can probably already see how a <code>Promise</code> is a much better data type (despite it implying async). It&#8217;s an immutable value, and the methods <code>then</code> and <code>catch</code> are already natively there for you. Also, no matter how many <code>then</code>&#8216;s or &#8220;rights&#8221;, 1 left can mess up the whole bunch, and it allllll flows down the single <code>catch</code> function for you. This is where composing Eithers (Promises in this case) is so powerful and helpful.</p>
<pre><code class="lang-javascript">const datBoom = () =&gt; Promise.reject('kapow');
const result = datBoom();
result
.then(data =&gt; console.log("data:", data))
.catch(error =&gt; console.log("error:", error));
</code></pre>
<p><a name="patternmatching"></a></p>
<h2 id="pattern-matching">Pattern Matching</h2>
<p>Whether synchronous or not, though, there&#8217;s a more powerful way to match the Either &#8216;esque types through pattern matching. If you&#8217;re an OOP developer, think of replacing your:</p>
<p><code>if ( thingA instanceof ClassA ) {</code></p>
<p>with:</p>
<p><code>ClassA: ()=&gt; "it's ClassA",<br />
ClassB: ()=&gt; "it's ClassB"</code>.</p>
<p>It&#8217;s like a <code>switch</code> and <code>case</code> for types.</p>
<p>Elixir does it with almost all of their functions (the _ being the traditional <code>default</code> keyword):</p>
<pre><code class="lang-elixir">case datBoom do
  {:ok, data}      -&gt; IO.puts "Success: #{data}"
  {:error, reason} -&gt; IO.puts "Error: #{reason}"
  _                -&gt; IO.puts "No clue, brah..."
end
</code></pre>
<p>In JavaScript, you can use the <a href="http://folktale.origamitower.com/api/v2.0.0/en/folktale.result.html">Folktale library</a>.</p>
<pre><code class="lang-javascript">const datBoom = () =&gt; Result.Error('kapow');
const result = datBoom();
const weGood = result.matchWith({
  Error: ({value}) =&gt; "negative...",
  Ok: ({value}) =&gt; "OH YEAH!"
});
console.log("weGood:", weGood); // negative...
</code></pre>
<p>Python has pattern matching with <a href="https://github.com/billpmurphy/hask">Hask</a> (although it&#8217;s dead project, <a href="https://github.com/evhub/coconut">Coconut</a> is an alternative):</p>
<pre><code class="lang-python">def datBoom():
  return Left('kapow')

def weGood(value):
    return ~(caseof(value)
                | m(Left(m.n)) &gt;&gt; "negative..."
                | m(Right(m.n)) &gt;&gt; "OH YEAH!")

result = datBoom()
print("weGood:", weGood(result)) # negative...
</code></pre>
<p>Scala does it as well, looking more like a traditional switch statement:</p>
<pre><code class="lang-scala">def weGood(value: Either): String = value match {
  case Left =&gt; "negative..."
  case Right =&gt; "OH YEAH!"
  case _ =&gt; "no clue, brah..."
}
weGood(Left('kapow'))  // negative...
</code></pre>
<p><a name="letitcrash"></a></p>
<h1 id="let-it-crash">Let It Crash</h1>
<p>The Mathematicians came up with Either. Three cool kats at Ericsson in 1986 came up with a different strategy in Erlang: let it crash. Later in 2009, <a href="https://akka.io/">Akka</a> took the same idea for the Java Virtual Machine in Scala and Java.</p>
<p>This flies in the face of the overall narrative of this article: don&#8217;t intentionally cause crashes. Technically it&#8217;s a supervised crash. The Erlang / Akka developers know errors are a part of life, so embrace they will will happen, and give you a safe environment to react to them happening without bringing down the rest of your application.</p>
<p>It also only becomes relatable if you do the kind of work where uptime with lots of traffic is the number one goal. Erlang (or Elixir) create processes to manage your code. If you know <a href="http://redux.js.org/">Redux</a> or <a href="http://elm-lang.org/">Elm</a>, the concept of a store to keep your (mostly) immutable data, then you&#8217;ll understand the concept of a Process in Elixir, and an Actor in Akka. You create a process, and it runs your code.</p>
<p>Except, the framework developers knew that if you find a bug, you&#8217;ll fix it and upload new code to the server. If the server needs to keep running to serve a lot of customers, then it needs to immediately restart if something crashes. If you upload new code, it needs to restart your new code as the older code processes shut down when they are done (or crash).</p>
<p>So, they created supervisors <a href="https://elixir-lang.org/getting-started/mix-otp/supervisor-and-application.html">Elixir</a>|<a href="https://doc.akka.io/docs/akka/current/scala/general/supervision.html">Scala</a>. Instead of creating 1 process that runs your code, it creates 2: one to run your code, and another to supervise it if it crashes, to restart a new one. These processes are uber lightweight (0.5kb of memory in Elixir, 0.3kb in Akka).</p>
<p>While Elixir has support for <a href="https://elixir-lang.org/getting-started/try-catch-and-rescue.html">try, catch, and raise</a>, error handling in Erlang/Elixir is a code smell. Let it crash, the supervisor will restart the process, you can debug the code, upload new code to a running server, and the processes spawned from that point forward will use your new code. This is similar to the immutable infrastructure movement around Docker in <a href="https://aws.amazon.com/ecs/">Amazon&#8217;s EC2 Container Service</a> and <a href="https://kubernetes.io/">Kubernetes</a>.</p>
<p><a name="conclusions"></a></p>
<h1 id="conclusions">Conclusions</h1>
<p>Intentionally crashing programs is a bad programming practice. Using <code>throw</code> is not the most effective way to isolate program problems, they aren&#8217;t easy to test, and can break other unrelated things.</p>
<p>Next time you think of using <code>throw</code>, instead, try doing an explicit return or an Either. Then unit test test it. Make it return an error in a larger program and see if it&#8217;s easier for you to find it given you are the one who caused it. I think you&#8217;ll find explicit returns or Eithers are easier to debug, easier to unit test, and can lead to more well thought out applications.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
