- Courses
- 💻Programming Languages
- 🐫OCaml (WIP)
- Functional Design Idioms
- Option/Result-Based Error Handling
On this page
Option/Result-Based Error Handling ("Railway-Oriented Programming")
Published on August 8, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Railway-oriented programming treats a sequence of operations that can each fail as a computation running on two parallel tracks: a success track and a failure track. Each step in the sequence is a function that takes a plain value and produces either a success or a failure — a switch, in the railway metaphor, connecting one incoming track to two possible outgoing ones. Chaining several such steps together should feel like connecting switches end to end, letting a value run all the way down the success track unless something diverts it onto the failure track, at which point every remaining step is automatically bypassed.
The Problem: Nested Matches Form a Staircase
Consider validating a signup form field by field: parsing an age from a string, then checking that age falls within an allowed range.
let parse_age s = int_of_string_opt s
let check_range age =
if age >= 0 && age <= 120 then Some age else None
Chaining these together with ordinary pattern matching works, but grows into a nested staircase as more steps join the chain:
let validate_age s =
match parse_age s with
| None -> None
| Some age ->
match check_range age with
| None -> None
| Some valid_age -> Some valid_age
Each additional fallible step adds another layer of nesting, another None -> None case repeating the same "just propagate the failure" logic, and pushes the actual success-path logic further to the right with every new step. This repetition is exactly the pattern railway-oriented programming is designed to eliminate.
bind: The Adapter That Connects Switches
The function that solves this is bind. Given a wrapped value and a function that takes a plain value and returns a new wrapped value, bind runs the function only if the wrapped value represents success, and passes an existing failure straight through untouched, without ever calling the function at all:
let bind opt f =
match opt with
| None -> None
| Some x -> f x
This is precisely the mechanism behind the railway analogy: bind is the adapter that lets a "switch" function, expecting a plain value, be connected onto the end of a track that's already carrying a wrapped one. If the incoming track is already on the failure side, the switch is bypassed entirely — its logic never runs, and the failure rides straight through to the end of the line. Option.bind and Result.bind in the standard library work exactly this way, for option and result respectively.
Chaining With the >>= Operator
Aliasing bind to an infix operator, conventionally >>=, makes a chain of fallible steps read left to right instead of nesting:
let ( >>= ) = Option.bind
let validate_age s = parse_age s >>= check_range
For a longer chain, >>= keeps composing the same way:
let ( >>= ) = Result.bind
let register email age =
parse_age age >>= fun a ->
check_range a >>= fun valid_age ->
check_email email >>= fun valid_email ->
Ok (valid_email, valid_age)
This is a real improvement over the nested-match staircase, but it has a readability wrinkle of its own: >>= associates to the right, which keeps a long chain free of extra parentheses, but can make it harder to see at a glance which anonymous function belongs to which step, especially once several fun x -> ... continuations stack up one after another.
Chaining With let*
Since OCaml 4.08, a dedicated binding operator syntax makes this same pattern read almost exactly like an ordinary sequence of let bindings. Defining let* as an alias for bind:
let ( let* ) = Result.bind
let register email age =
let* a = parse_age age in
let* valid_age = check_range a in
let* valid_email = check_email email in
Ok (valid_email, valid_age)
Each let* name = expr in binds name to the successful contents of expr and continues; if expr produces a failure instead, the whole function immediately evaluates to that failure, and none of the later let* lines ever run. This is the same underlying bind mechanism as the >>= version, just presented in a form that reads top to bottom exactly like ordinary variable binding — which is why let* has become the generally preferred way to write this pattern in current OCaml code, over both nested matching and the >>= operator.
Why Result, Not Option, for Real Pipelines
Option.bind and Result.bind share the exact same shape, but they carry very different amounts of information about a failure. option collapses every possible failure into the single value None — a chain of several Option.bind calls that fails somewhere in the middle produces None, with no indication of which step failed or why. result carries an actual payload in its failure case, Error of 'e, which means a chain built on Result.bind can report exactly what went wrong:
let parse_age s =
match int_of_string_opt s with
| Some n -> Ok n
| None -> Error (Printf.sprintf "%S is not a valid number" s)
let check_range age =
if age >= 0 && age <= 120 then Ok age
else Error (Printf.sprintf "%d is out of the valid range" age)
# parse_age "abc" |> Result.bind check_range;;
- : (int, string) result = Error "\"abc\" is not a valid number"
For a pipeline that a person or another system needs a meaningful explanation from when something fails, Result is almost always the better choice over Option for exactly this reason — the type of the error can carry as much detail as the situation calls for, from a plain string up to a full custom variant type distinguishing every possible failure case.
A Note on Terminology
The general shape behind this pattern — a type 'a t paired with a bind : 'a t -> ('a -> 'b t) -> 'b t function and a way to wrap a plain value (Some/Ok playing that role here) — is known more generally as a monad. Error handling through option and result is one of the simplest and most common examples of this pattern in OCaml, but the same shape reappears in other contexts, such as libraries that model asynchronous computation. Knowing the term is useful mainly for recognizing the same underlying structure elsewhere; nothing about using let* for error handling requires understanding monads as a general concept first.
Why This Composes Better Than Exceptions
An exception-based version of the same validation logic has no trace of its ability to fail anywhere in its type signature — validate_age : string -> int looks, from the outside, exactly like a function that always succeeds, and the only way to discover otherwise is to read its implementation or documentation, or find out directly at runtime. A Result-based version, validate_age : string -> (int, string) result, states the possibility of failure directly in its type, and let* composes a sequence of such functions without ever needing to leave that guarantee behind — every intermediate step in the chain is still an ordinary, referentially transparent function, and the compiler's exhaustiveness checking guarantees the eventual failure case gets handled somewhere, rather than potentially propagating, uncaught, all the way out of the program.
Key Takeaways
- Railway-oriented programming models each fallible step as a switch between a success track and a failure track; chaining steps together should propagate a failure automatically, bypassing every later step once one has occurred.
bind(Option.bindorResult.bind) is the adapter that makes this chaining possible: it runs the next step only on a success, and passes an existing failure through untouched.- The infix
>>=operator and thelet*binding operator both express the same chain ofbindcalls;let*generally reads more clearly, since it resembles an ordinary sequence ofletbindings read top to bottom. Resultis usually the better choice overOptionfor a real pipeline, since itsErrorcase can carry a description of what actually went wrong, whileOption'sNonecarries no information at all.- This general bind-and-wrap shape is known as a monad; recognizing the term is useful, but writing
let*-based error handling doesn't require understanding monads as a general concept. - A
Result-based chain keeps every step's ability to fail visible in its type, unlike an exception-based equivalent, while still composing as cleanly as a plain pipeline throughlet*.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Pipeline Composition
Next
Labeled & Optional Parameters
- The Problem: Nested Matches Form a Staircase
- bind: The Adapter That Connects Switches
- Chaining With the >>= Operator
- Chaining With let*
- Why Result, Not Option, for Real Pipelines
- A Note on Terminology
- Why This Composes Better Than Exceptions
- Key Takeaways
