Tour · 11 of 18
Typed errors
The program on the right fails to read a port and prints why.
#@error types
@error
enum ConfigError:
@error("port is not a number")
InvalidPort(@from error: ParseNumberError)An @error type keeps failures structured. Each case gets a display
message.
#@from
port := text.parse::[i32]()?@from generates the conversion this ? uses, from ParseNumberError to
ConfigError. It also records the parse error as the cause. Without
@from, ? has no conversion.
#Context
fn load(text: string) -> Result[i32, *dyn Error]:
parse_port(text).context("loading server config").context adds what the caller was doing. *dyn Error is a shared
reference to any error type.
#Reports
match load("eighty"):
.Ok(port) => println("port: $port")
.Err(error) => println(report_of(error))report_of turns the cause chain into text for display or logging.
Run it. "eighty" is not a number. So it prints the context, then each
cause on its own source: line.
Try it: change InvalidPort(@from error: ParseNumberError) to InvalidPort(error: ParseNumberError) and press Run.
Run: Ctrl+Enter · Pages: Alt+← Alt+→