Functional error handling in F# by example

Exceptions are bad.

Not only do we have to remember to catch them everywhere, they also provide a second implicit exit strategy for functions, similar to the goto statement.

However, there is an alternative more explicit approach.

In this post we will go through an example of how to implement decent functional error handling in F# without using NULL or exceptions.

We will do this by extending the application from the last post and make it even more reliable and robust.

The traditional way

Traditionally, failures are handled by either returning NULL, a special value (such as "", -1 or a NULL object), or by raising exceptions.

One of the problems with these approaches is that the caller always has to remember to do a thing. Furthermore the caller has, in general, no way of knowing whether a function might fail or not by only looking at its signature.

And there are more pitfalls (see Domain-Driven Design (DDD) With F# – Validation).

Representing potential failures with types

Most functional programming languages including F# have special types that can represent optional or missing values for example the Option type. A function that returns an Option<'a>, indicates that it might succeed and return Some<'a>, or that it might fail and return None.

The success and the failure case are explicitly represented by the type system.

The type system will check for us that we handle both cases when calling a function that returns an optional value. We don’t have to remember to do so. If we forget, the compiler will remind us because the application won’t compile!

It is impossible to overemphasize how valuable that is.

The Chessie project

In this post we will use the Result type which is slightly more advanced than Option.

A Result is defined like this:

type Result<'TSuccess, 'TMessage> = 
    | Ok of 'TSuccess * 'TMessage list
    | Bad of 'TMessage list

The advantage of the Result type is that it let’s us define error messages that we can return in case of failures. Furthermore we don’t have to hand-roll the generic error handling code.

Instead we can use the Chessie library which offers this type together with a very useful set of operations.

Implementing error handling and validation with the Result type is also sometimes called Railway Oriented Programming.

Note that there are a few other possibilities besides Chessie. There is the validation framework of Fsharpx.Extras or we could use ExtCore. There are also considerations to include the Result type into the F# language.

Extending an existing application

Here is the code of the application that we are going to extend. It is a very basic command line tool to manage the import of email addresses from a CSV file into a database. The little program is explained in more detail here. But the code is almost self-explanatory.

The application has 3 kinds of operations that could potentially fail:

  • Updating a database
  • Reading from a file (CSV and CONFIG files)
  • Parsing command line arguments

Line of action

To improve the application with decent error handling we need to take these 3 basic steps:

  • Define an appropriate message type
  • Make the failure cases explicit
  • Update the integration code

Before we begin we have to add a reference to Chessie for example by installing it from NuGet and add the import declaration open Chessie.ErrorHandling.

Defining an appropriate message type

There are many possibilities to define a type that represents a failure, or more general, a domain message.

In general the DomainMessage type should contain enough information to:

  • Display adequate and user-friendly error messages
  • Log everything needed for a detailed error analysis

Here is one possible definition:

type DomainMessage = 
    | DbUpdateFailure of Exception
    | CsvFileAccessFailure of Exception
    | CliArgumentParsingFailure of Exception
    | ConfigurationFailure of Exception

The DomainMessage type is defined as a discriminated union with one case for each of the general types of failures mentioned above.

In some of these cases there are more sub-types of possible failures. For example, when updating the database we could get an Invalid column name, a violation of primary key or some other error.

Note that each union case holds a value of type Exception. This makes sense in this scenario. However, we can use any kind of value (or combination of values) that suits our needs.

Making the failure cases explicit

Changing the implementations of the unsafe functions is quite easy.

We will just wrap all the code that accesses external data sources in try catch statements.

If an exception is caught, we will return a DomainMessage wrapped in a Bad case of the Result type. Otherwise we will return the result value wrapped in the Ok case.

As this strategy is always the same, we will create a higher-order function to reduce code duplication:

// val tryF : f:(unit -> 'a) -> msg:(exn -> 'b) -> Result<'a,'b>
let tryF f msg =
    try f() |> ok with ex -> fail (msg ex)

In the beginning I stated that throwing exceptions is bad. However, if it is an external library that is throwing exceptions we cannot help, but handle them as close as possible to where they occur.

Here is one example

We will only look at one example because it will always be the same.

This was the original code for reading from the CSV file:

// val readFromCsvFile : fileName:string -> MailingListEntry list
let readFromCsvFile (fileName:string) = 
    let data = MailingListData.Load(fileName)
    [for row in data.Rows do
        yield { Email = Email row.Email; Name = Name row.Name}]

Here is the new version:

// val readFromCsvFile : fileName:string -> Result<MailingListEntry list,DomainMessage>
let readFromCsvFile (fileName:string) = 
    let read () =
        let data = MailingListData.Load(fileName)
        [for row in data.Rows do
            yield { Email = Email row.Email; Name = Name row.Name}]
    tryF read CsvFileAccessFailure

The signature of readFromCsvFile now looks like this:

val readFromCsvFile : fileName:string -> Result<MailingListEntry list,DomainMessage>

That means if the operation succeeds, the function will return a list of MailingListEntry. Otherwise it will return a DomainMessage.

Likewise we will change all the other functions…

The database accessing functions in the module DataAccess will now have these signatures:

val insert : cs:string -> list:MailingListEntry list -> Result<unit,DomainMessage>

val delete : cs:string -> Result<unit,DomainMessage>

The function that parses the command line arguments in the module Arguments will have this signature:

val getCmds : args:string [] -> Result<CliArguments list,DomainMessage>

To retrieve the connection string from the configuration file we will just directly bind the result to the value csResult of type Result<string, DomainMessage> like this:

// val csResult : Result<string, DomainMessage>
let private csResult =
    tryF (fun () -> Settings.ConnectionStrings.MyMailingListDb) ConfigurationFailure

Updating the integration code

Now we have to put everything together.

Normal function application won’t work anymore because the types have changed and don’t match.

Therefore we will use the composition mechanisms of the Result type.

In this case we will compose the functions with the bind operator or with >>= (the infix version of bind).

Note that there is also the composition with apply which we won’t cover here.

Injecting the connection string

First we have to partially apply the database access functions to the connection string which is wrapped in a Result and bound to csResult:

// val import : list:MailingListEntry list -> Result<unit,DomainMessage>
let import list = csResult >>= fun cs -> DataAccess.insert cs list
// val delete : unit -> Result<unit,DomainMessage>
let delete() = csResult >>= DataAccess.delete

Another option would be to use a computation expression. In this case that is the trial computation expression provided by Chessie:

let import list = trial {
    let! connectionString = csResult
    let! result = DataAccess.insert connectionString list
    return result }

The result is the same.

For more information on this particular kind of computation expression please refer to Composition with an Either computation expression.

In cases when the expression is more complex I would prefer the computation expression because it is much more readable. In this case, though, I prefer using the infix bind operator because it is much more concise. I think that computation expressions are more idiomatic in F#, but at the end it’s a matter of taste.

Handling a single command

To update the handle function we will only replace the pipe operator |> with the >>= operator:

// val handle : cmd:CliArgument -> Result<unit,DomainMessage>
let handle cmd =
    match cmd with
    | Import fileName -> readFromCsvFile fileName >>= import
    | Delete          -> delete()

I find this quite elegant, in fact. To me this is a soft indication of how sound the concept of functional error handling is.

Processing a list of commands

Next we have to update the function that processes the list of commands.

Original implementation:

// val run : args:string [] -> unit
let run args =
    getCmds args
    |> List.iter handle

This is just a bit more tricky. And there are a few ways to do this.

So let’s think about what the return type of our new version should be?

The original implementation of run returns unit which indicates the absence of a specific value. So the return type that we want to achieve is Result<unit, DomainMessage>.

Let’s try to map the handle function over the list of CliArguments that is wrapped in a Result with Trial.lift:

getCmds args |> Trial.lift (Seq.map handle)

This will return a Result<seq<Result<unit,DomainMessage>>,DomainMessage> which is quite unwieldy, though.

So one possible solution is to use Trial.collect to convert a list of results into a result of a list:

Seq.map handle >> Trial.collect

If at least one of the results is a failure, only errors will be collected and returned.

Now, because this returns a Result<unit list, DomainMessage>, we can use the >>= operator again:

// val run : args:string [] -> Result<unit list,DomainMessage>
let run args =
    getCmds args >>= (Seq.map handle >> Trial.collect)

Again there is an explicit version with the trial computation expression:

trial {
    let! cmds = getCmds args
    let! result = cmds |> Seq.map handle |> Trial.collect
    return result }

Note that both versions return unit list (instead of a single value of type unit) wrapped in a Result. This could be fixed easily. For example we can map ignore over it. However it doesn’t make a difference in this particular situation.

When we use Trial.collect we have to be careful about the behavior.

Since handle is not a pure function all side effects of the successful operations will occur even if there are errors and the overall result is a failure.

A different approach

An alternative approach would be to fold over the list of CliArguemtns with bind.

This would also change the behavior.

In the first version all commands will be handled and afterwards the errors will be collected if there are any.

The alternative behavior is to abort the processing as soon as the first error occurs. We can achieve this with a fold:

// val handleMany: args:seq<CliArguments> -> Result<unit,DomainMessage>
let handleMany args = 
    args |> Seq.fold (fun result next -> result >>= fun _ -> handle next) (ok ())

Next we can bind handleMany to the result of getCmds args:

// val run : args:string [] -> Result<unit,DomainMessage>
let run args = getCmds args >>= handleMany

The main method

Finally in the main method we can:

  • Process the command line arguments
  • Pattern match on the result
  • In case of failure(s) display (and log) helpful error messages
[<EntryPoint>]
let main argv = 
    let result = run argv

    match result with
    | Ok _     -> do printfn "SUCCESS"
    | Bad errs -> do errs |> List.iter handleError
    0

The complete code is available on GitHub .

Conclusion

Traditional error handling has many pitfalls.

The alternative to traditional error handling is functional error handling which represents potential failures explicitly with the type system.

In this post we have seen an example of how to extend an existing application with functional error handling in F#.

The concept, especially the composition part, is not totally easy to understand if you’re new to functional programming.

In my opinion, the key to understanding is to try it out and use it. This is why I presented an example rather than explaining too many details.

For more information on the details please refer to Railway Oriented Programming and The “Map and Bind and Apply, Oh my!” series.

Another tutorial with examples in F# and C# you can find here: Error handling with Applicative Functors in F# and C#.

Once you get a hang of it, you’ll love it. I promise!

If you have any questions or comments, please let me know or leave a comment here.