Haskell World logo Haskell WorldWrite code, build worlds
Programming

Haskell Either for Error Handling Without Exceptions

Your Haskell service crashes at 3 a.m. with an uncaught exception from a config parser, and the stack trace tells you almost nothing.

A laptop on a wooden desk showing a code editor with two panes of functions, beside a notebook with hand-drawn arrows branching left and right

Your Haskell service crashes at 3 a.m. with an uncaught exception from a config parser, and the stack trace tells you almost nothing. The fix most teams reach for is Haskell Either: a plain data type that makes failure part of the function's signature, so the compiler forces every caller to deal with it.

This guide walks through how Either works, how to chain it without drowning in case expressions, where it beats exceptions, and the places where it honestly does not.

What Haskell Either actually is

Either has two constructors. Left holds the failure, Right holds the success. A function with the type String to Either ParseError Config tells you, before you read a single line of its body, that it can fail and what the failure looks like.

The convention that Left means error is not enforced by the type itself. It comes from the Functor and Monad instances, which only touch the Right side. When you fmap a function over a Right value, the function runs. When you fmap it over a Left value, nothing happens and the Left passes through untouched. That single rule is what makes Either work as an error type.

If you have already read about how the Maybe type replaces null in Haskell, Either is the next step. Maybe says "something went wrong." Either says "something went wrong, and here is exactly what."

A first example

Picture a function called parsePort that takes a String. If the string is not a number, it returns Left with the value InvalidNumber. If the number is outside 1 to 65535, it returns Left with PortOutOfRange and the number itself. Otherwise it returns Right with the port.

Chaining Either without nested case expressions

The first time people use Either, they write a case expression for every call. Parse the host, case on it. Parse the port, case on it. Parse the timeout, case on it. By the fourth field the code drifts off the right edge of the screen.

The Monad instance removes all of that. Inside a do block, each line that returns an Either either produces a value for the next line or stops the whole block with the first Left it hits. A loadConfig function can read host, port and timeout in three lines, then build the record on the fourth. If the port is bad, the timeout is never parsed, and the caller receives Left PortOutOfRange 70000.

This is the same mechanism explained in understanding monads in Haskell without the metaphors: bind looks at the value, and if it is a Left, it skips everything after it.

Useful helpers from base

  • either takes two functions, one for Left and one for Right, and collapses the value. It is the cleanest way to turn a result into a log line or an HTTP response.
  • traverse runs a function returning Either over a list and stops at the first failure. Parsing 200 rows of a CSV file becomes one line.
  • first from Data.Bifunctor changes the error type without touching success. You will use it constantly to adapt one module's errors to another's.

Designing error types that stay useful

The most common mistake is making the Left side a String. It compiles, it feels quick, and six months later you have code that does string matching on error messages to decide whether to retry. That is worse than exceptions.

Use a sum type per module instead. A config module might have MissingKey with the key name, InvalidNumber with the raw text, and PortOutOfRange with the integer. Each constructor carries the data a caller needs to act, not just a sentence for a human.

A newtype around a domain ID pairs well with this. If you have seen the ideas in Haskell newtype patterns that prevent real production bugs, an error like UserNotFound UserId is far more useful than UserNotFound Int, because nobody can accidentally stuff an order number into it.

Left typeGood forMain drawback
String or TextThrowaway scripts, prototypesCallers cannot branch on it safely
Module sum typeLibraries and service layersNeeds mapping at module edges
One giant app error typeSmall apps with few modulesEvery module depends on every error

The common advice to ban exceptions is wrong

You will read that idiomatic Haskell should replace every exception with Either. That advice sounds principled and breaks down quickly in IO-heavy code.

Exceptions in Haskell exist for reasons Either cannot cover. A database connection dropping, a disk filling up, an async thread being killed by a timeout: these can happen at any point in IO code, and pretending otherwise by wrapping every IO action in ExceptT gives you two error channels instead of one. ExceptT does not catch an IOException thrown from inside it. You still need bracket and finally for cleanup.

A rule that holds up in production is simpler. Use Either for expected failures that are part of your domain: invalid input, missing records, business rule violations. Let exceptions handle unexpected failures from the runtime and the outside world, and catch them at one boundary, usually the request handler or the main loop.

Either in a real request handler

Here is how the pieces fit in a typical JSON endpoint that creates an order.

  1. Decode the request body. Aeson's eitherDecode already returns Either String with the parse error, so map it into your own BadRequest constructor with first.
  2. Validate the fields with a pure function returning Either ValidationError ValidOrder. No IO, so it is trivial to test with QuickCheck.
  3. Run the database insert in IO. Let connection failures stay as exceptions. Return Left OutOfStock only for the expected business case.
  4. At the handler edge, use either to map every Left to a status code: 400 for bad input, 409 for stock problems, and let a top level catch return 500 for anything thrown.

The result is a handler where every 4xx response is visible in the types, and the 5xx path lives in exactly one place.

When to reach for Validation instead

Either stops at the first failure. For a signup form with eight fields, that means a user fixes the email, resubmits, then learns the password is too short, then learns the username is taken. Three round trips for one form.

The Validation type from the validation or either packages has the same shape but an Applicative instance that collects every Left into a list or a NonEmpty. It has no Monad instance on purpose, because later steps cannot depend on earlier results if all steps must run. Use Validation for independent field checks, then convert to Either once you need sequencing.

Frequently asked questions

Is Either faster than throwing exceptions in Haskell?

In pure code the difference is small, and GHC often optimises Either chains well after inlining. Exceptions can be cheaper on the success path because nothing is allocated, but they are harder to reason about. Choose based on whether the failure is expected, not on speed, unless profiling shows a real hotspot.

Why is the error on the Left side of Either?

The Functor and Monad instances for Either only map over the last type parameter, which is the Right side. So the success value has to sit on the right for fmap and do notation to work on it. The mnemonic that "right" means correct is a happy accident that most people find easy to remember.

Should I use ExceptT or plain Either in IO code?

Plain Either returned from IO actions is often enough, and it avoids a transformer layer. ExceptT helps when you have long chains of IO steps that each can fail with a domain error. Keep it local to one module rather than putting it at the base of your whole application stack.

FB
Finnian Burke

Finnian Burke spent eight years building distributed systems before leaving to write about the programming patterns that actually hold up under pressure. He has worked with Haskell, Rust, and Go in production, and writes mostly about the parts of functional programming that turn out to be useful regardless of the language you use day to day.

More posts by Finnian

More in Programming

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto