Errors as Values
Result, Option, propagation, boundary conversion, and the difference between failure and bugs.
Contents
Haze has no exceptions and no unwrap. An operation that can fail returns a Result, an operation that can be absent returns an Option, and the caller handles the outcome with match, is, or ?. This chapter explains how to design those types and how to keep error handling out of the domain logic.
Failure Versus Bugs#
The first decision is whether the situation is an expected failure or a bug. An expected failure is part of the operation's contract with the caller: a file may be missing, input may be malformed, a remote service may refuse a 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, an invariant that no longer holds.
Expected failures are values. Bugs are handled by preconditions, postconditions, and invariants. A runtime contract violation panics; a Result is returned. Mixing the two produces APIs that are neither total nor honest.
| 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 | Panic, because the caller has a bug |
| An invariant would be violated | Checked construction | Error returned by ? |
| An internal invariant is broken | Postcondition or assert in a test |
Panic or test failure |
Choosing Option or Result#
Use Option when absence is a normal state and there is no useful reason to report. Use Result when the caller needs a reason, when different failures require different recovery, or when the 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 }?)
}
The first function answers "where is it, if anywhere?" The second answers "is this value valid, and if not, why?" The distinction is about what the caller can do with the answer, not about severity.
An Option can be converted to a Result at the point where the reason becomes relevant.
fn required(value Option[i32], name str) Result[i32, str] => match value {
Some(number) => Success(number)
None => Error($"missing {name}")
}
The conversion is explicit, so the caller sees where the missing reason is introduced.
Designing an Error Type#
A Result error type should be as precise as the caller needs. 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" })
}
The sum lets a caller match each case and produce a specific message or recovery. A string error forces the caller to parse the message or treat every failure the same.
An error record is useful when the failure carries several pieces of context that are not alternatives.
type ParseFailure {
input str
offset i32
reason str
}
fn parse(text str) Result[Value, ParseFailure] {
// ...
}
The record is not a sum because every failure has the same shape. Choose the representation that matches the information the caller needs.
Propagating with ?#
? is the concise way to propagate 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)
}
read_file and parse_i32 must both return Result[_, ConfigError]. If they return different error types, map the error 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))
}
The explicit mapping is more verbose, but it makes the error translation visible. Use ? when the error domain is already correct; use match when the boundary changes the error domain.
Parse at the Boundary#
The most effective error-handling pattern is to parse untrusted input once and then work with precise types. The parser returns a structured error; the domain code receives a value that is already valid.
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
After parse_age, can_vote does not need to check the range. The type carries the guarantee. The boundary has one error path, and the domain has none.
A parser should preserve enough context to produce a useful message. An InvalidDigit(position, character) error is more useful than a generic "invalid input" string, and a Missing(path) error 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. A function that can return a default should return the default, not a Result that the caller will always unwrap.
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 }
age_in_days is total because Age is validated. set_name requires a non-empty name; the precondition is the right mechanism because an empty name is a caller error, not an expected runtime failure.
The overuse of Result is a common mistake in languages that have just discovered errors as values. It pushes handling to every caller and makes the code look more dangerous than it is. Reserve Result for operations with genuine expected failure.
Error Context and Recovery#
A caller should be able to recover without reconstructing context from a message. The error type should carry the path, the identifier, the offset, or whatever the caller needs to make a decision.
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 recovery path can then match the error and produce a user-facing message or a corrected action. A string error would force the caller to compare text, which is brittle and cannot be checked by the compiler.
Errors and Contracts#
A contract should not restate an expected failure. If a function returns Result for an expected failure, its precondition should describe the domain that is still required, not the failure that the Result models.
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,
})
}
The precondition says that a non-positive amount is a caller bug. The insufficient-funds case is an expected failure because the caller may legitimately ask for more than the balance and handle the refusal. Checked construction is different: an invalid refinement is an expected failure when the input is runtime data, so it returns Error rather than panicking.
Composing Fallible Operations#
A sequence of fallible operations is a sequence of ? bindings. The error type stays consistent, and the success path reads like ordinary code.
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))
}
}
When the error types differ, map at the boundary. When a failure should be recovered locally, use match. When a failure should be enriched with context, wrap it in a larger error type.
fn load_port_or_default(config Config) Port => match load_port(config) {
Success(port) => port
Error(_) => Port { 8080 }
}
The recovery is explicit. The caller can see the default and decide whether it is appropriate.
Testing Error Paths#
Every error variant should have at least one test that reaches it. A test that only checks the success path leaves the error construction and the caller's handling unverified.
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(_)
}
When the error payload matters, bind it and assert the fields. When the error is a sum, match it and assert the variant. The Testing Contracts chapter gives the pattern.
Summary#
| Decision | Idiomatic 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 |
The next chapter, The FFI Boundary, explains why crossing into C gives up these guarantees and how to keep the boundary as small as possible.