v0.4.0
Errors · Lesson 9.10

Error mapping

Source
Pass an error to the caller as your own error type with try call catch { e => throw Mapped(e) }, adding context such as a line number.
You'll need: Fail, Propagate

A low-level function knows what went wrong but not where. ParseNumber can say "the character at position 2 is not a digit", but it has no idea that its text came from line 3 of a settings file. The function that does know is the one calling it.

This lesson shows how that caller adds what it knows to the error as it passes through, with try call catch { e => throw Mapped(e) }.

Plain try cannot add context

Two error types meet here. ParseNumber throws a DigitError, which knows a position; the settings reader throws a SettingError, which needs a line and a column:

struct DigitError {
    position: uint;
}

struct SettingError {
    line: uint;
    column: uint;
}

Plain try passes an error on unchanged, so it cannot add the line number — and it is rejected here anyway, because a DigitError is not a SettingError. The compiler's note is worth reading: an error "is never converted" on its way out.

A catch arm that throws maps the error

The mapped form fixes both problems:

let w = try ParseNumber(width) catch { e => throw SettingError { line: 1, column: e.position + 1 } };
let h = try ParseNumber(height) catch { e => throw SettingError { line: 2, column: e.position + 1 } };
PieceMeaning
try ParseNumber(width)on success, the number; the arm never runs
catch { e => ... }on failure, e is the whole original DigitError
throw SettingError { ... }the new error, built from e and anything else in scope; the function throws it
flowchart LR
    invoke["`try ParseNumber(width)`"] --> q{"Success or error?"}
    q -- "success" --> n["the number;<br/>the arm never runs"]
    q -- "error, as `e`" --> m["the arm builds<br/>`SettingError { line: 1, column: e.position + 1 }`"]
    m --> f["`WindowArea` throws<br/>the new error"]

The throw in the arm leaves the function directly; it is not caught by the same catch again. An arm that throws produces no value, so it never has to match the success type.

The arm uses what is in scope

The arm can read anything the function can. Here it adds the line number, which only WindowArea knows, and turns the 0-based position into the 1-based column a person would look for. In "8O" the letter O sits at position 1, so the message says column 2.

The thrown value must have the function's error type, a SettingError — the compiler checks that, but not whether the arithmetic inside is right.

Where to map

Map an error where the context is. ParseNumber stays small and reusable because it knows nothing about files; WindowArea is the first function that knows about lines, so it is the one that maps. Its own caller then deals with SettingError alone and never needs to know that a DigitError existed.

The program

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

Src/Main.rux
// A low-level function knows what went wrong but not where. `ParseNumber` below
// can say "the character at position 2 is not a digit", but it has no idea that
// its text came from line 3 of a settings file. The function that *does* know
// is the one calling it.
//
// Plain `try` passes an error on unchanged, so it cannot add that context — and
// it is rejected here anyway, because a `DigitError` is not a `SettingError`
// and an error is never converted on its way out. The mapped form fixes both:
//
//     try ParseNumber(text) catch { e => throw SettingError { ... } }
//
// On success the expression is the number and the arm never runs. On failure
// `e` is the whole original error, the arm builds the new one from `e` plus
// anything else in scope, and throws it. That `throw` leaves the function
// directly; it is not caught by the same `catch` again.
import Io::PrintLine;

struct DigitError {
    position: uint;
}

struct SettingError {
    line: uint;
    column: uint;
}

// Knows about characters, nothing about files or lines.
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;
}

// Reads a window size from two settings lines. Each `catch` arm adds the line
// number, which only this function knows, and turns the 0-based position into
// the 1-based column a person would look for.
func WindowArea(width: char8[..], height: char8[..]) -> int throws SettingError {
    let w = try ParseNumber(width) catch { e => throw SettingError { line: 1, column: e.position + 1 } };
    let h = try ParseNumber(height) catch { e => throw SettingError { line: 2, column: e.position + 1 } };
    return w * h;
}

func Show(width: char8[..], height: char8[..]) {
    try {
        let area = WindowArea(width, height);
        PrintLine("{} x {}: area {}", width, height, area);
    } catch {
        e => PrintLine("{} x {}: line {}, column {} is not a digit", width, height, e.line, e.column)
    }
}

func Main() -> int {
    Show("80", "24");
    Show("8O", "24");
    Show("80", "2-4");
    return 0;
}

Run it

cd Examples/Errors/ErrorMapping
rux run
80 x 24: area 1920
8O x 24: line 1, column 2 is not a digit
80 x 2-4: line 2, column 2 is not a digit

Common mistakes

Try it yourself

  1. Add a found: char8 field to SettingError and fill it in the arm with the bad character, width[e.position]. Print it in Show.
  2. Call Show("", "24"). Predict the output before you run it — is an empty line an error?
  3. Read a third setting, a depth on line 3, and print the volume instead of the area.

Learn more