Errors as Values
Result, Option, propagation, boundary conversion, and the difference between failure and bugs.
Contents
There are no exceptions and no unwrap. An operation that can fail returns a Result; an operation that can be absent returns an Option.
Failure Versus Bugs#
An expected failure is part of the operation's contract with the caller: a missing file, malformed input, a refused request. A bug is a violation of a stated domain: a negative count passed to a function that requires a positive one, an index outside a list.
Expected failures are values. Bugs are handled by preconditions, postconditions, and invariants. A runtime contract violation aborts; a Result is returned.
| Situation | Return type | Failure path |
|---|---|---|
| A file may not exist | Result[File, FsError] |
Error(NotFound(path)) |
| A list may be empty | Option[T] or Result[T, E] |
None or Error |
| A parser may reject input | Result[Value, ParseError] |
Structured error |
| A caller passed a negative count | Precondition | Abort, because the caller has a bug |
| An invariant would be violated | Checked construction | Error returned by ? |
| An internal invariant is broken | Postcondition or test assertion | Abort or test failure |
Option or Result#
Use Option when absence is normal and there is no useful reason to report. Use Result when the caller needs a reason, when different failures require different recovery, or when failure crosses a boundary.
type Positive = i32 : invariant self > 0
fn find(values List[i32], target i32) Option[i32] {
for i in 0..values.len {
if values[i] == target {
return Some(i)
}
}
return None
}
fn require_positive(n i32) Result[Positive, str] {
if n <= 0 {
return Error("value must be positive")
}
return Success(Positive { n }?)
}
fn required(value Option[i32], name str) Result[i32, str] => match value {
Some(number) => Success(number)
None => Error($"missing {name}")
}
Designing an Error Type#
A str is convenient for a small helper or a user-facing message. A sum type is better when different failures require different handling.
type ConfigError =
| Missing(path str)
| Invalid(path str, line i32)
| Unreadable(path str)
fn load_config(path str) Result[Config, ConfigError] {
if path.len == 0 {
return Error(Missing(path))
}
return Success(Config { name = "default" })
}
An error record is useful when every failure has the same shape but carries several pieces of context.
type ParseFailure {
input str
offset i32
reason str
}
fn parse(text str) Result[Value, ParseFailure] {
// ...
}
Propagating with ?#
? propagates an error when the current function has nothing useful to add. The enclosing function must return a Result with exactly the same error type.
fn read_number(path str) Result[i32, ConfigError] {
const text = read_file(path)?
return parse_i32(text)
}
When the error domain changes, map explicitly.
fn read_number(path str) Result[i32, ConfigError] => match read_file(path) {
Success(text) => match parse_i32(text) {
Success(number) => Success(number)
Error(_) => Error(Invalid(path, 0))
}
Error(_) => Error(Unreadable(path))
}
Parse at the Boundary#
Parse untrusted input once, then work with precise types.
type Age = i32 : invariant self >= 0 && self <= 150
fn parse_age(text str) Result[Age, str] {
const value = parse_i32(text)?
return Success(Age { value }?)
}
fn can_vote(age Age) bool => age >= 18
Preserve context in the error. InvalidDigit(position, character) is more useful than "invalid input"; Missing(path) is more useful than a boolean.
Do Not Return Result for Everything#
A function that cannot fail should return a plain value. A function whose only failure is a caller bug should use a precondition.
fn age_in_days(age Age) i32 => age * 365
fn set_name(account Account, name NonEmpty) Account
: pre name.len > 0
=> Account { id = account.id, name = name }
Reserve Result for operations with genuine expected failure.
Error Context and Recovery#
The error type should carry the path, identifier, offset, or other data the caller needs to decide what to do.
type TransferError =
| AccountMissing(id i32)
| InsufficientFunds(available i64, requested i64)
| SameAccount(id i32)
fn transfer(source i32, target i32, amount i64) Result[Receipt, TransferError] {
if source == target {
return Error(SameAccount(source))
}
// ...
}
A caller can match the error and produce a message or corrected action. A string error would force text comparison.
Errors and Contracts#
A contract should not restate an expected failure.
fn withdraw(account Account, amount i64) Result[Account, str]
: pre amount > 0
{
if amount > account.balance {
return Error("insufficient funds")
}
return Success(Account {
id = account.id,
balance = account.balance - amount,
})
}
A non-positive amount is a caller bug. Insufficient funds is an expected failure. Checked construction is also an expected failure because the input is runtime data.
Composing Fallible Operations#
A sequence of fallible operations is a sequence of ? bindings when the error type is consistent.
type Port = i32 : invariant self > 0 && self <= 65535
type Config {
port_text str
}
fn check_port(number i32) Result[Port, str] => Success(Port { number }?)
fn load_port(config Config) Result[Port, ConfigError] {
return match parse_i32(config.port_text) {
Success(number) => match check_port(number) {
Success(port) => Success(port)
Error(_) => Error(Invalid("port", 0))
}
Error(_) => Error(Invalid("port", 0))
}
}
Map at the boundary when error types differ, and use match when a failure should be recovered locally.
fn load_port_or_default(config Config) Port => match load_port(config) {
Success(port) => port
Error(_) => Port { 8080 }
}
Testing Error Paths#
Every error variant should have a test that reaches it.
test "withdraw rejects an overdraft" {
const account = Account { id = 1, balance = 10 }
assert withdraw(account, 50) is Error(_)
}
test "withdraw succeeds within the balance" {
const account = Account { id = 1, balance = 50 }
assert withdraw(account, 10) is Success(_)
}
Summary#
| Decision | Answer |
|---|---|
| Expected failure | Result[T, E] |
| Absence with no reason | Option[T] |
| Caller violated a domain | Precondition |
| Implementation violated a guarantee | Postcondition |
| Invalid refinement from runtime data | Checked construction |
| Error reason the caller needs | Sum type or record |
| Error reason that is only a message | str |
| Propagating the same error domain | ? |
| Changing the error domain | match and map |
| Recovering locally | match or is |
| Unwrapping | Never; there is no unwrap |