RFD-0005 Haskell error handling

Introduction

This RFD outlines a convention for error handling in Haskell code. This was a richer field than anticipated. We keep several of the references that we investigated in the References section, and a glossary with many of the terms that became relevant while we decided on the final proposal.

The Evaluation of alternatives section explains the final convention.

Goal

Define a precise way to define interfaces that support errors and exceptions our my codebase.

Vision

We comfortably manage exceptional cases in our code, both in pure and monadic style. Our interfaces are ergonomic, and adapting interfaces from others isn’t too cumbersome.

Principles

  • Weight papers more than blogs.

  • Favour rigour over convenience.

We ideally want a style that supports:

  • Code with exceptions is pure when it doesn’t evaluate to a exceptional value. That is snd (partial a, partial b) does not depend on partial a not throwing an exception.

  • When pure code evaluate to an exception value, it crashes the program with a useful stack trace.

  • Code in IO can safely catch exceptions from pure code to perform error recovery (not for control flow).

Evaluation of alternatives

Introduction

There are many ways to handle errors in Haskell: Maybe, Either, error, throw, throwIO, fail, MonadError, MonadFail, MonadThrow, and more. Without clear guidelines, we must decide which approach to use in every situation;a daunting task given the number of options. Similar situations may lead to different choices and inconsistent code.

By establishing a few guiding principles and following them consistently, we avoid repeated decisions and keep the codebase uniform.

Error handling convention

Our goal is to write code that is simple, efficient and checked by the Haskell’s type system at compile time. When a function may fail, we can signal failure with an exception, or we can return a product type to explicitly represent success or failure. Often a failure simply aborts the computation and lets a higher level error handler inform the user (for example, printing an error message and terminating the program). Exceptions are ideal for this. They keep the code simple and give the compiler greater freedom to optimise. However, if the program logic depends on the error value, exceptions result in more complicated code with weaker type guarantees. In this case, return types such as Maybe or Either e are better.

Our libraries will typically implement both interfaces, allowing users to use the one that fits their needs. Application code, however, will more often use exceptions, as programs typically abort when they operate on invalid data.

When a library provides a function with both interfaces, we distinguish them adding a suffix to its name:

  • Either or Maybe if the function returns an explicit error value.

  • Throw if the function throws an exception.

If we expect one interface to be used more often, we can provide an alias without suffix. Often, however, we leave that choice to the application code.

For example, a library could implement head like this:

headMaybe :: [a] -> Maybe a
headMaybe []    = Nothing
headMaybe (a:_) = Just a

headThrow :: [a] -> a
headThrow []    = error "Using headThrow on []"
headThrow (a:_) = a

An application can then define:

head :: [a] -> a
head = headThrow

or

head :: [a] -> Maybe a
head = headMaybe

If most applications used the same head implementation, the library can provide that one to avoid duplication.

Error types

The cause of an error is often irrelevant, so prefer the simpler Maybe a to represent a value that may be of type a or an error. When the cause matters, we use Either e a, which allows programs to use e in their logic.

Since we intend to use e for control flow, we avoid types such as free-form text or SomeException. These require parsing the error reason or casting down exceptions down weakening the guarantees provided by the type system.

Exceptions

We use error "some message" to throw an exception in pure code.

Since no program logic should depend on the exception’s value, a simple Text or String message is enough to describe the error.

error "message" is an imprecise exception, which is a value, not a computation. Haskell raises an exception only when this value is evaluated.

For computations in IO, we use unliftIO's throwIO to abort explicitly with an exception. RFD 0007 addresses the design of error handling for IO libraries.

This code illustrates the difference between error and throwIO:

pure (error "foo")
>> putStrLn "not aborted"
>> throwIO (userError "ouch")
>> putStrLn "should've aborted"

error is never evaluated, so it has no effect. The code prints not aborted and then aborts with Exception: user error (ouch) when evaluating throwIO.

Prior work

This RFD builds heavily on the paper A semantics for imprecise exceptions.

Tweag’s Three kinds of haskell exceptions and how to use them reaches similar conclusions as we did, and also goes more in depth about how to safely catch exceptions in IO.

References

System.IO.Error

Definition of IOError, type tests and functions to throw and catch them.

Control.Exception

Built-in and user defined exceptions.

A sematics for imprecise exceptions

paper describing imprecise exceptions in Haskell.

Three kinds of haskell exceptions and how to use them

How Tweag uses exceptions.

Exceptions best practices in Haskell

FP Block documents antipatterns and good patterns in exception handling.

Glossary

Imprecise exception

A given computation may raise several distinct exceptions. Haskell guarantees that a catch will observe some exception, but neither specifies which one nor guarantees that repeated evaluations of the same computation will yield the same exception. I’m not aware of a formal, authoritative definition;. The closest approximation is the following statement from the absract of "A sematics for imprecise exceptions":

Some modern superscalar microprocessors provide only imprecise exceptions. That is, they do not guarantee to report the same exception that would be encountered by a straightforward sequential execution of the program. […​]. In this paper we propose a design for imprecise exceptions in the lazy functional programming language Haskell. […​] We sketch a precise semantics for the language extended with exceptions.

The paper includes a formal algebraic definition of Haskell’s imprecise exceptions.

Relevant functions and types

SomeException

Exception that simply wraps another exception of a generic type. Relies on cast to recover the wrapper exception.

TODO Explain how it gets created and how it is safely downcasted.

General exceptions

error

HasCallStack ⇒ String → a, throw an imprecise exception wrapping String.

throwIO

(HasCallStack, Exception e) ⇒ e → IO a. Interrupt an IO computation throwing a synchronous, precise exception.

throw

forall a e. (HasCallStack, Exception e) ⇒ e → a throws an imprecise exception, but constraining the wrapped type to the Exception type class. Throws an imprecise exception.

catch

(MonadUnliftIO m, Exception e) ⇒ m a → (e → m a) → m a catches a synchronous exception.

try

(MonadUnliftIO m, Exception e) ⇒ m a → m (Either e a) catches exceptions into the left side of Either.

bracket

MonadUnliftIO m ⇒ m a → (a → m b) → (a → m c) → m c run cleanup after a computation (the cleanup cannot be interrupted).

MonadFail

MonadFail is used to desugar pattern matching within do blocks.

fail

MonadFail m ⇒ String → m a Fails within the monad, in IO it uses failIO which throws SomeException.

It has instances for MaybeT.

MonadError

This type class is polymorphic on the error type e, which gives us instances for Either e a and Maybe ().

In principle, we could chose to use it for both disaster recovery and alternative return, however it forces the user to always use monadic code, which effectively puts error recovery and alternative returns in the same code structure.

It has instances for ExceptT

MonadThrow

Type class for non polymorphic monads, roughly equivalent to Exception e ⇒ MonadError e. We now have instances for Maybe, Either e, and IO. Having an IO instance is attractive in that we could use pure code directly in IO or in alternative result style by choosing the IO instance or the Either e and Maybe instances.

Still, the same objection as using MonadError applies.

It has instances for MaybeT and ExceptT (and Maybe and Either).

ExceptT

Monad transformer polymorphic on the error type. This gives us a direct instance for MonadError. We can use ExceptT to lift an alternative return Either e into error recovery style, but we can only run directly in IO if the error type is String.

TODO Examples and explain how the instances go.

MaybeT

Gives us a MonadFail instance.

ErrorT