Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Pattern Matching and Options

Result and Error Handling

Learn error handling in F#: the Result type with Ok and Error, Result.map and bind, validation with custom error unions, exceptions with try/with, and railway-oriented programming.

Option tells you that something is missing, but not why. When a caller needs the reason (bad input, a failed rule, a missing file), F# gives you Result. It is the type-safe alternative to throwing exceptions for expected failures, and it fits the pipeline style that the rest of the language uses.

Ok and Error

Result is another discriminated union, with two type parameters:

FSHARP
type Result<'T, 'TError> =
    | Ok of 'T
    | Error of 'TError
FSHARP
let parseAge (text: string) : Result<int, string> =
    match System.Int32.TryParse text with
    | true, n when n >= 0 && n <= 150 -> Ok n
    | true, _ -> Error "age out of range"
    | false, _ -> Error $"'{text}' is not a number"

match parseAge "42" with
| Ok age -> printfn "age %d" age
| Error msg -> printfn "problem: %s" msg

The signature string -> Result<int, string> says plainly: this may fail, and the failure is a string. The error type can be anything, but a union of error cases is better than a string because callers can match on it and the compiler tracks what can go wrong.

FSHARP
type AgeError =
    | NotANumber of text: string
    | OutOfRange of value: int
C# C# stand-in: a small Result type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Result.map, Result.bind and Result.mapError

Like options, results have a module of combinators:

FSHARP
parseAge "30" |> Result.map (fun a -> a + 1)             // Ok 31
parseAge "x"  |> Result.map (fun a -> a + 1)             // Error "'x' is not a number"
parseAge "x"  |> Result.mapError (fun e -> e.Length)     // Error 18
  • Result.map changes the success value and passes errors along.
  • Result.mapError changes the error value (useful for converting between layers).
  • Result.bind chains a step that may itself fail.
  • Result.defaultValue, Result.isOk, Result.toOption leave result-land.
FSHARP
let validateName (name: string) =
    if System.String.IsNullOrWhiteSpace name then Error "name is required" else Ok name

type Person = { Name: string; Age: int }

let makePerson name ageText =
    validateName name
    |> Result.bind (fun n ->
        parseAge ageText
        |> Result.map (fun a -> { Name = n; Age = a }))

This is nested like the option version. The result { } computation expression (FSharp.Core 9+; use a library such as FsToolkit.ErrorHandling on older versions) flattens it:

FSHARP
let makePerson2 name ageText =
    result {
        let! n = validateName name
        let! a = parseAge ageText
        return { Name = n; Age = a }
    }

The first Error stops the block and becomes the result. That is the whole idea.

Railway-oriented programming

A popular way to picture this: each function is a section of railway with two tracks. Success continues on the happy track; any failure switches to the error track and rides to the end, skipping everything in between.

flowchart LR
    I["input"] --> V["validate"]
    V -->|Ok| P["parse"]
    P -->|Ok| S["save"]
    S -->|Ok| R["Ok result"]
    V -->|Error| E["Error result"]
    P -->|Error| E
    S -->|Error| E

Two tracks: Result.bind connects the steps, so one failure skips the rest and surfaces at the end.

The result is a clean top-level function that reads like the business rule, while the plumbing of "stop if anything went wrong" is handled once, by bind.

Collecting all errors

bind stops at the first error. For form validation you often want every problem at once. A simple approach: validate each field to its own result, then combine:

FSHARP
let combine (a: Result<'a, string>) (b: Result<'b, string>) =
    match a, b with
    | Ok x, Ok y -> Ok (x, y)
    | Error e1, Error e2 -> Error [ e1; e2 ]
    | Error e, _ | _, Error e -> Error [ e ]

Libraries such as FsToolkit.ErrorHandling provide a validation { } workflow with and! that does this properly; the core idea is the same as above.

Exceptions: when they still belong

Exceptions are for the unexpected: a bug, a disk failure, an impossible state. F# has the usual forms:

FSHARP
let readFirstLine path =
    try
        Ok (System.IO.File.ReadLines(path) |> Seq.head)
    with
    | :? System.IO.FileNotFoundException -> Error "file not found"
    | ex -> Error ex.Message

let risky () =
    try
        failwith "boom"
    finally
        printfn "cleanup runs either way"

failwith "msg" raises a general exception; invalidArg and raise (MyException ...) are more specific. try ... with returns a value just like match, and try ... finally guarantees cleanup (though use is usually neater). A good rule: convert exceptions into Result at the boundary (file, network, parsing), and keep the inside of your program in result-land.

You can declare a lightweight exception with exception:

FSHARP
exception ValidationFailed of string

try raise (ValidationFailed "bad input")
with ValidationFailed msg -> printfn "caught: %s" msg

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Result<int, string> tell the caller?

    A result is a union of success and failure; both outcomes are visible in the type.
  2. 2. What does Result.bind do with an Error value?

    bind runs the next step only for Ok, so the first Error short-circuits the chain.
  3. 3. Which function converts the error part of a result?

    mapError transforms Error values and leaves Ok untouched.
  4. 4. Where should exceptions be converted into Result values?

    Catch at the edge, then keep the core free of exceptions.

Summary

  • Result<'T, 'E> models success or a described failure; prefer a union of error cases to strings.
  • Result.map, mapError and bind transform and chain results; result { } flattens longer chains.
  • Railway-oriented style: steps connected so any failure skips the rest and surfaces at the end.
  • Collect several errors by combining results (or use a validation library).
  • Exceptions are for the unexpected; convert them to Result at the boundary.

Next: Active Patterns