v0.4.0
Errors · Lesson 9.11

Error sum

Source
Let one function throw either of two error types, throws DigitError | RangeError, and tell them apart with typed patterns in catch.
You'll need: Outcome, Propagate

Some functions can fail in more than one unrelated way. Reading a percentage can find a character that is not a digit, or a perfectly good number that is bigger than 100. Those are two different error types, and the throws clause can name both.

Two errors in one clause

The two errors are separate structs, each with its own details:

struct DigitError {
    position: uint;
}

struct RangeError {
    value: int;
    limit: int;
}

ParsePercent names both after throws:

func ParsePercent(text: char8[..]) -> int throws DigitError | RangeError {

A | B is a sum: one value that is an A or a B, and knows which. Sums have a part of their own, Sum types, straight after this one; here you need only what it means after throws. The order does not matter — RangeError | DigitError is the same type. No parentheses are needed: the error is the whole type after throws, so the | belongs to it.

Widening needs no code

The surprise is how little the function body has to do:

let value = try ParseNumber(text);
if value > 100 {
    throw RangeError { value: value, limit: 100 };
}
return value;

ParseNumber throws a plain DigitError, yet try passes it on unchanged — a DigitError fits into the wider sum on its own. throw RangeError { ... } needs no wrapping either. This is called widening: a narrower error always fits into a sum that includes it.

flowchart LR
    d["`ParseNumber` throws<br/>a `DigitError`"] -- "`try`" --> sum["`ParsePercent` throws<br/>`DigitError | RangeError`"]
    r["`throw RangeError { ... }`"] --> sum
    sum --> m{"The caller's `catch`"}
    m -- "`e: DigitError`" --> a["`no digit at position …`"]
    m -- "`e: RangeError`" --> b["`… is over 100`"]

Telling the members apart

The caller tells the members apart with a typed pattern. e: DigitError matches only that member and binds it as a plain DigitError, so its fields are right there:

try {
    let percent = ParsePercent(text);
    PrintLine("{:5} -> {}%", text, percent);
} catch {
    e: DigitError => PrintLine("{:5} -> no digit at position {}", text, e.position),
    e: RangeError => PrintLine("{:5} -> {} is over {}", text, e.value, e.limit)
}

The arms must cover every member of the sum, or the compiler names the missing one.

A sum or a variant?

Error variant solved a similar problem with one type and several cases. Both work; they suit different situations.

Error sum A | BError variant
The errors areseparate types that already existcases you declare together
Passing one on with trywidens on its ownneeds a mapping into a case
Adding a new kind of errorchanges every signature that lists the sumone new case in one declaration
Best forcombining errors from different placesa stable, named set of failures

The program

The whole lesson is one package in the Examples repository. Its comments explain every step.

Src/Main.rux
// Some functions can fail in more than one unrelated way. Reading a percentage
// can find a character that is not a digit, or a perfectly good number that
// is bigger than 100. Those are two different error types, and the `throws`
// clause can name both:
//
//     func ParsePercent(text: char8[..]) -> int throws DigitError | RangeError
//
// `A | B` is a sum: one value that is an `A` or a `B`, and knows which. The
// order does not matter — `RangeError | DigitError` is the same type.
//
// The surprise is how little the function body has to do. A `DigitError`
// fits into the wider sum on its own, so `try ParseNumber(text)` passes it on
// unchanged and `throw RangeError { ... }` needs no wrapping either. This is
// called widening: a narrower error always fits into a sum that includes it.
import Io::PrintLine;

struct DigitError {
    position: uint;
}

struct RangeError {
    value: int;
    limit: int;
}

func ParseNumber(text: char8[..]) -> int throws DigitError {
    var total = 0;
    for i in 0..text.length {
        let byte = text[i];
        if byte < c8'0' || byte > c8'9' {
            throw DigitError { position: i };
        }
        total = total * 10 + ((byte as int) - 48);
    }
    return total;
}

func ParsePercent(text: char8[..]) -> int throws DigitError | RangeError {
    // A `DigitError` widens into the sum as `try` passes it on.
    let value = try ParseNumber(text);
    if value > 100 {
        throw RangeError { value: value, limit: 100 };
    }
    return value;
}

// The caller tells the members apart with a typed pattern: `e: DigitError`
// matches only that member and binds it as a plain `DigitError`. The arms
// must cover every member of the sum, or the compiler names the missing one.
// Drop the `RangeError` arm and it says "match on 'DigitError | RangeError'
// is not exhaustive; missing _: RangeError".
func Show(text: char8[..]) {
    try {
        let percent = ParsePercent(text);
        PrintLine("{:5} -> {}%", text, percent);
    } catch {
        e: DigitError => PrintLine("{:5} -> no digit at position {}", text, e.position),
        e: RangeError => PrintLine("{:5} -> {} is over {}", text, e.value, e.limit)
    }
}

func Main() -> int {
    Show("75");
    Show("7%");
    Show("250");
    return 0;
}

Run it

cd Examples/Errors/ErrorSum
rux run
75    -> 75%
7%    -> no digit at position 1
250   -> 250 is over 100

Common mistakes

Try it yourself

  1. Add Show("100"); and Show("101"); and predict both lines.
  2. Show("") prints 0%. Add an EmptyError struct, put it in the sum, and throw it on empty text. What else does the compiler ask you to change?
  3. Swap the order of the members in the signature to RangeError | DigitError and check that nothing else has to change.

Learn more