Skip to content

Failure

29. Pick the tool by what happens on failure

Section titled “29. Pick the tool by what happens on failure”

Writing a function that cannot take every input. When some input has no answer, pick the first of these that fits (spec §4 Subtypes, §11 Traps, Maybe and Result; tour: Pattern Matching):

  1. Type it. When the requirement is about one argument’s value alone and a pure rule can check it, take a subtype: a count is a NonNegativeInt, a buffer size a PositiveInt, a list that must have an element a NonEmptyList. A literal argument is checked when the program is compiled. A check narrows a binding (spec §4 Narrowing), and arithmetic keeps what its range proves (spec §4 Value ranges): after if d == 0 then return Err(.DivisionByZero), d is a NonZeroInt, and after if size > 1, size - 1 is a PositiveInt, so a computed value often needs no try_from. Write the check where the code already makes it; a value no check covers pays one try_from where it enters. Two arguments that must agree are one value with a rule: a range, or a struct with a when.
  2. Define it. When an input that looks wrong has the meaning a caller would want, give it that meaning: String.take(s, -1) is "", and timer.sleep with a negative duration returns at once. Define only the meaning a caller would expect, never a guess that hides a bug: a chunk size of 0 has none, so Iter.chunks takes a PositiveInt.
  3. Return Maybe when absence is an ordinary outcome that depends on the data: a lookup that may miss, find, the first element of a list that may be empty. Where a subtype proves the value is there, give that subtype a function that answers it plainly, as NonEmptyList.first does.
  4. Return Result when the failure has a reason worth reporting, or comes from outside the program: a parse, input, a file, the network.
  5. Trap only on a caller’s mistake that no type carries at a fair cost and no Maybe can answer. A zero divisor is not one: / takes a NonZeroInt, so a divisor is checked first or typed. An index past the end depends on another value, so Vector.get and Vector.set return Maybe, and a caller that computed the index writes !. A trap reports a bug; nothing in the program catches it. Say in the doc comment what traps, make the message name the bad value, and give the caller a total way around it: a sibling that returns Maybe, or a cheap check to run first.

A failed task is the one trap that crosses a boundary: Task.await propagates the trap of the task it waits for, and the cancellation of a cancelled one, to the code that awaits it. That is by design. The trap was a bug in the task’s body, and it surfaces as it would have had the body run inline; an Err the body returned is a value and arrives as one. Where a task’s failure is an outcome rather than a bug, because the code cancelled the task or runs work whose failure it reports, wait with Task.outcome, the total form, which returns how the task ended as an Outcome.

Write the function once, returning a Maybe or a Result, as std’s get does, and let a caller that knows the call cannot fail write ! after it:

// the index comes from data: the miss is an outcome
case Vector.get(row, column)
    Some(cell) -> cell
    None       -> blank
end

// the index is within bounds by construction: a miss is a bug
middle = Vector.get(sorted, Vector.length(sorted) / 2)!

Don’t return a Maybe whose None every caller must unwrap with an “impossible” arm: that arm is untested code, and it hides the bug a trap would report at its line. Don’t trap on data from outside the program either; a missing key in a config file is something to report, not a crash.

Taking a result apart. Five constructs take a value apart when it might not have the shape you want. Choose by what the failure path does:

  • ? passes the error up unchanged. Use it when the function returns a Result or a Maybe and the caller should handle this step’s failure as it is. In a pipe, write it after the stage (§7).
  • ! traps. Use it when a failure would be a bug and the expression itself explains it: constant arguments (Date.new(2024, 1, 1)!), a key taken from the map itself, an index the code computed in range, input already validated. Its trap quotes the expression and shows the error, so the reader of the trap needs nothing more.
  • A binding else (Pattern = value else ...) handles or replaces one step’s failure in place: it returns a different error, skips a loop item, or supplies a fallback, and the success path continues unindented.
  • case when both outcomes continue with work of their own.
  • if Pattern = expr when only the success branch needs the names and a miss does nothing (§24).
// ?: the caller gets load's error as it is
user = load(id)?

// else: the error is replaced with one that says which user
Ok(user) = load(id) else
    Err(.NotFound) -> return Err("no user ${id}")
    Err(e)         -> return Err("loading user ${id}: ${e}")
end

// else: a fallback stands in for the missing value
Some(email) = user.email else "none"

// else: skip what does not parse
Iter.each(lines, fn line ->
    Ok(entry) = parse(line) else continue
    record(entry)
end)

// case: both outcomes do work
case load(id)
    Ok(user) -> greet(user)
    Err(e)   -> log_failure(e)
end

// if: only a match does anything
if Some(email) = user.email then send(email)

Prefer a binding else to a case whose failure arm only leaves: the case would nest the whole success path one level in. Prefer ? to an else whose arm returns the same error unchanged (Err(e) -> return Err(e)).

That reason holds only when work follows the binding. When the only line after an else whose arms return is the function’s last expression, write a case: the success path is one arm, nothing is nested, and no arm needs return.

// not: a binding used once, and a return in every arm
fn find_post(id: Int) -> Result<Post, NotFound>
    Ok(Some(post)) = posts.by_id(id) else
        Ok(None) -> return Err(NotFound{id:})
        Err(_)   -> return Err(NotFound{id:})
    end

    Ok(post)
end

// but
fn find_post(id: Int) -> Result<Post, NotFound>
    case posts.by_id(id)
        Ok(Some(post)) -> Ok(post)
        Ok(None)       -> Err(NotFound{id:})
        Err(_)         -> Err(NotFound{id:})
    end
end

State an invariant with unreachable. When a Maybe or a case arm can only miss because of an invariant the reader cannot see from the call, write a binding else with unreachable and the invariant as its reason. A made-up default would hide the bug instead:

// every student is in Student.variants(), so the search cannot miss
fn position(student: Student) -> Int
    Some(i) = Student.variants() |> Iter.find_index(&(&1 == student)) else
        unreachable "every student is listed"
    end
    i
end

Maybe.with_default(0) in its place returns 0 for a student someone forgot to list, and nothing flags it. The reason is the claim a reader checks, so state the invariant, not the symptom: “every student is listed”, not “not found”. Never use unreachable or ! for data from outside the program: one after parsing a line of input claims something the program does not control, and a failure that can really happen is a Maybe or a Result to handle. When the claim is only that one value is there, ! states it where the value is read: Date.new(year, 1, 1)!, not a binding else with unreachable "1 January exists".

Turn a missing value into an error with a binding else when the value is bound for the lines that follow, and with Maybe.to_result and a ? after it when the lookup is one stage of a pipe. Name the variant with its enum in to_result: nothing at that position fixes the error type, so .NotFound alone cannot be resolved there.

// bound for later lines
Some(user) = Map.get(users, id) else return Err(.NotFound)

// one stage of a pipe
count =
    word
    |> String.trim()
    |> String.to_int()
    |> Maybe.to_result(Error.NotANumber)?

When a signature is settled and its body is not, write todo with a reason (spec §11 Unwritten code; tour: Functions & Lambdas) rather than a value that happens to type-check:

fn parse(text: String) -> Header
    todo "parse the header"
end

A made-up Header{name: "", size: 0} runs and returns a wrong result that nothing flags; todo stops the program at the line that is missing, the editor lists it as a warning, and nomi build refuses to ship it. Give a reason when the next step is not obvious from the signature, and keep it to what is left to do. Use todo while writing code, not as a permanent marker for a case that cannot happen: such a case is better shaped out of the types, and where the types cannot say it, unreachable "reason" states the invariant (§29). One that can happen deserves a real result or an Err.