Posted on by & filed under Content - Highlights and Reviews, Programming & Development.

error messageIn the interest of clarity we will not worry too much about error handling.” (Advanced Perl Programming by Sriram Srinivasan)

This was the attitude toward error handling until very recently. Errors were called side-effects, and scientists were busy inventing languages that had no side effects (hence, no errors). Then monads were discovered, and now we can deal with an imperfect world. Erik Meijer said that every programming language works within some kind of monad.

Opinions vary though on how we think about the surrounding monad. In Java, people are used to exceptions and nulls. If the data is missing, we pass around a null. If the data is wrong, we throw an exception.

Scala is richer, and nulls are discouraged. Exceptions are rare, but they do happen, and some alternatives are: Option, Either, scalaz.Validation. You can find some details about Scalaz in Chapter 6.3. Introducing the Scalaz HTTP module in Scala in Action.

Option is good for extending a partial function to a total function: for instance, if we want to return a head of a list, and the list is empty, a good solution would be to use list.headOption instead. This returns Some(head) or None if there’s no head (and no tail). Option is also good for wrapping null: Option(null) == None. The problem with Option is that if we have None, we are clueless as to what happened. That’s where Either becomes more useful.

Either[L,R] has two implementations, Left[L] and Right[R]. Traditionally Left[L] is used to store error reports, and Right[R] is used for passing around valid results. Beats me, why Left is bad and Right is good, but that’s not the problem. The problem is the symmetry of Left and Right, while in real life we would prefer an asymmetry: one kind of operation (like map, filter, etc.) available on good data, and another (concatenating, catching exceptions, etc.) on bad data.

scalaz.Validation shows the difference between Success and Failure. Here is a good example of its usage (source:

Here, ValidationNEL means that error messages, if found, are stored in a Non-Empty List. The last line in the code either produces a list of error messages, or a tuple (name,address) that is used for instantiating a person.

scalaz.Validation is almost perfect, except that I ran into trouble using it in my practice. I had no clue how to deal with the case when there’s no result at all. Exceptions and nulls coming from external sources, and are not handled.

So I decided to write my own version, with the strict purpose of usability.

The trait is called Result[T], and has three implementations: Good[T], Bad[T], and Empty.

All of the usual methods are here: isGood, isBad, onError, map, flatMap and filter. The latter takes a predicate (T=>Boolean) and an error message.

To walk through alternatives, you can write val res1:Result[T] = res orElse /* something else*/; having a partial function pf:PartialFunction[T,U], you can call res.collect(pf, errorMessage) to either produce a new Good[T] or a new Bad[T] with the error message.

Having res1:Result[T] and res2:Result[U], you can blend them (that’s an applicative functor) into res1 <*> res2 of type Result[(T,U)], which would be Bad(msg1::msg2::Nil) if both res1 and res2 are Bad.

Since Result is applicative, we can use it to traverse:

This works if you have a collection of results, but you need just one result (containing a collection of values), or on error you want to list all of the errors encountered while scanning the collection.

What’s more important, Result(null) will return Empty, and Result(throw new Exception(“oops”)) will return a Bad.

Now, here is a practical example:


Now we can do this:

Here, from a map props, we can extract values if they are available, parse the date of birth if it is valid, and return a Good[Person] or report missing data as Bad(errors). All of the complexity is hidden, and the application code reads pretty much as if we did not care about errors at all, like it was in the times of Perl programming.

You can access the code for this solution at

Safari Books Online has the content you need

Check out these Scala books available from Safari Books Online:

Scala in Action is a comprehensive tutorial that introduces Scala through clear explanations and numerous hands-on examples. Because Scala is a rich and deep language, it can be daunting to absorb all the new concepts at once. This book takes a “how-to” approach, explaining language concepts as you explore familiar programming challenges that you face in your day-to-day work.
This book takes a step-by-step tutorial approach to teaching you Scala. Starting with the fundamental elements of the language, Programming in Scala introduces functional programming from the practitioner’s perspective, and describes advanced language features that can make you a better, more productive developer.
Scala in Depth is a unique new book designed to help you integrate Scala effectively into your development process. By presenting the emerging best practices and designs from the Scala community, it guides you though dozens of powerful techniques example by example.

About the author

Vlad Patryshev was born in Russia, and has an education in Math (including now popular category theory). Since 1998 in the US, he worked at Borland (JBuilder team), then at Google in various teams, and had a 20% project, an onscreen keyboard, now available on various Google pages. He then changed several Bay Area startups, and now is working at A functional programmer and a Scala fan since 2008, he is now an organizer of Scala BASE and Bay Area Categories and Types meetups. As a hobby, he rides his road bike, builds decks, and drives around the US (Key West to the Polar Circle in Alaska). He can be reached at @vpatryshev.

Tags: Either, Errors, Nulls, Option, Scala, Scalaz, validation,

Comments are closed.