title: Either for error handling in java
body: <p>My new workplace is heavily using functional java Either for its error handling (<a href="http://www.functionaljava.org/javadoc/4.5/functionaljava/fj/data/Either.html" rel="noreferrer">http://www.functionaljava.org/javadoc/4.5/functionaljava/fj/data/Either.html</a>). </p>
  
  <p>exceptions are almost not used at all. </p>
  
  <p>This is very annoying imo for many reasons. To name one:
  Every api call (which returns an Either) inside a method, must first check if the returned Either is an error or not before continuing to the next line. If it is an error, it is propogated back in the stack of method calls in an a form of an Either. Each method up in the stack will also need to check the retunred Either for the error, until finally we will get to the method that is responsible for handling the error.
  This results in a very badly structued java code. i cant really write a normal flow java code as i have to "stop" on every api call (so streams are out of the question). for example</p>
  
  <pre><code>Either&lt;Error, Value&gt; myMethod(String someVar) {
       Either&lt;Error, Value&gt; valEither someService.getSomething(someVar)
       if (valEither.isRight()) {
          Either&lt;Error, Value&gt; otherValue someService.getSomethingElse(valEither.right().value())
          if (otherValue.isRight()) ..... //you get the idea
       } else {
          //maybe log
          return valEither;
      }
  }
  </code></pre>
  
  <p>I can, of course, use the monadic methods of Either (which i do) but that will not solve the core issues of having to "ask" the return type if its an error or a value.
  There are a lot more reasons why i think using Either as an infrastructure for error handling is not a good idea (long assigments statments, long methods, nested generics etc.).</p>
  
  <p>To work around it, I thought of maybe throwing a specific exception for every  api call which returns an "error" Either, and catch the exception once, on the top level method im currently working on. </p>
  
  <pre><code>Value val = myService.getSomething().rightOrThrow(new MyException("blaa"));
  </code></pre>
  
  <p>but that doesn't seem to be possible as the only method on the Either projection type which does something similiar, is throwing a java Error, which is not meant to be caught under (almost) any circumstances (I can accidently catch a stackoverflow or outofmemory errors).</p>
  
  <pre><code>myService.getSomething().right().valueE("some error msg");
  </code></pre>
  
  <p>Any suggestions or thoughts?</p>
  
  <p>Thanks</p>