Skip to content
Kavachकवच

Adding Context

● Intermediate3 minBefore this: trySpec 5.7

context adds a short note to an error that try passes on, so the message says what was being done.

fn read_port(text: String) -> Int ! Error {
    Int(text) catch _ => fail Error("not a number: {text}")
}

fn load_settings(port_text: String) -> Int ! Error {
    try read_port(port_text) context "loading settings"
}

fn main() {
    const port = load_settings("80a") catch e => {
        print("{e}")
        0
    }
    print(port)
}

The program ran and printed:

kavach run context.kav

loading settings: not a number: 80a0
context.kav: Kavach code, then what running it prints

The message becomes loading settings: not a number: 80a. The original error is kept inside, so a caller can still match on it, whatever context was added:

use std.fs

fn load(path: String) -> String ! Error {
    try fs.read_text(path) context "loading settings"
}

fn main() {
    const text = load("app.toml") catch e => match e {
        FsError.NotFound(p) => "no {p}: {e}",
        _ => "something else: {e}",
    }
    print(text)
}

The program ran and printed:

kavach run match-error-context.kav

no app.toml: loading settings: NotFound(path: "app.toml")
match-error-context.kav: Kavach code, then what running it prints