Error Handling
No Exceptions
Functions that can fail return Result(value, error). Values that might be
absent are Option(value). Errors are values — visible in types, mandatory
to handle:
match parse_int(input) {
Ok(n) -> use(n)
Err(e) -> handle(e)
}
A Result that stands as a statement cannot be dropped by accident: with
nothing looking at it, it is an error, this `Result` is unused: an error in it would go unseen; handle it, return it with `?`, or write `let _ = ...` .
Typed Stdlib Errors
Every fallible stdlib module returns a typed error enum — IoError,
JsonError, TomlError, IntError, FloatError, HttpError, TcpError,
PostgresError, TimeError, BytesError, UrlError, CryptoError,
UuidError and RegexError; no function returns a Result(_, String).
Each is named after its module and is a member of it (io.IoError), and so are its variants: io.NotFound,
json.Syntax, http.Timeout, and so on; where the platform can report
more than the list (a file system, a socket, a server), the last variant
is Other(String). The full
catalog is in docs/stdlib/errors.md; hovering
over an error type in your editor shows the same table.
You can either pattern-match on a specific variant, or show the error, which gives its message:
import io
import string
fn main() {
match io.read_file("app.json") {
Ok(content) -> println("loaded {string.length(content)} bytes")
Err(io.NotFound(path)) -> println("file does not exist: {path}")
Err(io.PermissionDenied(path)) -> println("denied: {path}")
Err(e) -> println("error: {e}")
}
}open in playgroundA stdlib error enum is shown as its message: "{e}", println(e) and
the error: line of a main that returns Err(e) all give that text. An
error type of your own is shown as any type is, by its structure
(Bad("x")), unless you write a Display impl for it:
type ConfigError {
Missing(String),
Bad(String),
}
trait Display for ConfigError {
fn display(self) -> String {
match self {
Missing(key) -> "missing key: {key}"
Bad(s) -> "bad input: {s}"
}
}
}
fn main() {
println(Bad("x"))
println("{Missing("port")}")
}open in playgroundIt prints bad input: x and missing key: port.
The ? Operator
? propagates errors to the caller unchanged. It works on both Result and
Option, and it does not convert between error types — the inner Err
type of the ?-ed expression must match the enclosing function’s Err
type:
import io
fn read_head(path: String) -> Result(String, io.IoError) {
let content = io.read_file(path)? -- Err(IoError) propagates
Ok(content)
}
? and the pipe operator
A ? that ends a pipeline applies to the whole pipeline — no parentheses
needed:
import io
import result
type Wrap {
Wrap(io.IoError),
}
fn load(path: String) -> Result(String, Wrap) {
let raw = io.read_file(path) |> result.map_err { e -> Wrap(e) }?
Ok(raw)
}
fn main() {
match load("config.toml") {
Ok(_) -> println("loaded")
Err(_) -> println("no config")
}
}open in playgroundx |> f |> g? parses as (x |> f |> g)?. On the other side, produce()? |> double
still works too — the ? on the left is already attached by the time the
pipe sees the value.
Everywhere else ? binds tightly, like a call: it applies to the operand
right before it. int.parse(a)? + int.parse(b)? adds two unwrapped values,
a == b? is a == (b?), and -x? is -(x?). To unwrap the result of an
infix expression, parenthesise it: (a + b)?.
Err escaping main
main returns () or Result((), e), so ? works at the top level too,
and it is how a tool fails: the Err is the program’s message to its user.
How main ends | What silt run does |
|---|---|
it returns () or Ok(()) | exit status 0 |
it returns Err(e) | the one line error: e on stderr, exit status 1 |
a runtime error or a panic that no task.guard catches | the error with its place and calls on stderr, exit status 1 |
The error: e line is the program’s own text, written exactly as the
program made it, colours and other control characters included. A
panic’s text, and the report of a runtime error in a task, are silt’s
reports of a fault: the program’s text in them shows
each control character (a carriage return, a tab, an escape sequence) or
invisible character as an escape (\r, \t, \u{1b}), as silt’s other
messages show a value, so it cannot move the cursor, colour or clear the
terminal. Its line ends stay: the lines after the first are a note.
The payload is shown as println shows it, so a tool’s own error type
with a Display impl reads as the tool writes it. Where that impl itself
fails (a panic in it, a division by zero, a failed task.join), the
payload is shown by its structure, and one line under it says which
impl failed, what its failure said and where:
error: E { a: 1 }
note: the Display impl of E failed: panic: display panics (main.silt:3:32)
The note names the innermost Display impl that showing the payload
ran when it failed: the payload’s own, or that of a part of it (a
record’s field, an item of a list), also of a part an impl shows in an
interpolation. A function or another trait’s method that the impl calls
is that impl’s code. The note gives the first line of the failure’s
message, at most 1,000 bytes of it. A test that
returns such an Err has the same note in its report. A process.exit
in the impl still ends the program. Its type must have
Display: a function, a channel, or a type that holds one and has no
Display impl, is refused when the program is checked (and so is the
error type of a test function).
-- noexec
import io
fn main() -> Result((), String) {
match io.args() {
[] -> Err("logq: no input files")
paths -> {
println("reading {paths}")
Ok(())
}
}
}open in playground$ silt run logq.silt
error: logq: no input files
A test function that returns Err(e) fails, and its report names the
test (see Testing).
process.exit is the one way to end with another code. A tool that wants
its own message and code says so:
import int
import io
import process
fn main() {
match int.parse("forty") {
Ok(n) -> println(n)
Err(e) -> {
io.eprintln("count: {e}")
process.exit(2)
}
}
}open in playgroundCatching a Runtime Error: task.guard
A runtime error (a panic, a division by zero, a failed join) is not a
value: it ends the work it is raised in. task.guard(work) makes it one.
It runs work and gives Ok of its value, or Err(e) for a runtime
error raised inside it, e a task.RuntimeError with the error’s
message, its location and the trace of calls that led there.
Shown, e is the report the program would have printed:
import task
fn ratio(a: Int, b: Int) -> Int {
a / b
}
fn shown(r: Result(Int, task.RuntimeError)) -> String {
match r {
Ok(v) -> "{v}"
Err(e) -> "skipped: {e.message}"
}
}
fn main() {
println(shown(task.guard { -> ratio(6, 3) })) -- 2
println(shown(task.guard { -> ratio(1, 0) })) -- skipped: division by zero
}open in playgroundThe function runs in place, on the caller’s task, so a guard costs about
what a call costs. What ends the program on purpose, or by a fault of
silt or its host, passes through a guard: process.exit, a deadlock of
the program’s thread, a stop of the task (a task.deadline whose time
passed, a helper whose body returned), an embedder’s step budget used up.
See task.guard.
Cross-Module Error Composition
? does not convert between typed errors, so a function that calls several
stdlib modules — each returning its own error enum — needs a local wrapper.
The canonical pattern: declare an AppError enum, lift each call via
result.map_err, and let ? propagate uniformly:
import http
import io
import json
import result
import url
type Config {
api_url: url.Url,
api_key: String,
}
type AppError {
ConfigRead(io.IoError),
ConfigParse(json.JsonError),
ApiCall(http.HttpError),
}
fn load_and_fetch(path: String) -> Result(Bytes, AppError) {
let contents = result.map_err(io.read_file(path)) { e -> ConfigRead(e) }?
let config = result.map_err(json.parse(contents, Config)) { e -> ConfigParse(e) }?
let resp = result.map_err(http.get(config.api_url)) { e -> ApiCall(e) }?
Ok(resp.body)
}
Variant constructors like Wrap or ConfigRead are first-class Fn values,
so result.map_err(r, ConfigRead) also works with no closure wrapping.
See examples/cross_module_errors.silt
for the full worked example.
when let-else for Custom Errors
When you need a custom error message or destructuring that goes beyond ?:
fn parse_config(text) {
let lines = text |> string.split("\n")
when let Some(host_line) = lines |> list.find { l -> string.contains(l, "host=") } else {
return Err("missing host in config")
}
let host = host_line |> string.replace("host=", "")
when let Some(port_line) = lines |> list.find { l -> string.contains(l, "port=") } else {
return Err("missing port in config")
}
when let Ok(port) = port_line |> string.replace("port=", "") |> int.parse else {
return Err("invalid port number")
}
Ok("connecting to {host}:{port}")
}
Choosing Between ? and when let-else
Use ? when you want to propagate the error unchanged. Use when let-else
when you need to:
- Provide a custom error message
- Destructure something other than
ResultorOption - Combine pattern and boolean guards in a flat sequence
-- Simple propagation: use ?
let value = parse(input)?
-- Custom error message: use when let-else
when let Ok(value) = parse(input) else {
return Err("failed to parse input: expected integer")
}
-- Mixed pattern and boolean guards
fn process(input) {
when let Ok(value) = parse(input) else { return Err("parse failed") }
when value > 0 else { return Err("must be positive") }
Ok(value * 2)
}
Never Type
return and panic() produce the Never type, which unifies with any
type. This lets them appear in any expression position:
fn get_or_die(opt) {
match opt {
Some(v) -> v
None -> panic("expected a value") -- Never unifies with v's type
}
}
A function may say that it never returns: -> Never as its return type.
Its body must not end: it ends in panic, in a call of another function
that returns Never, or in a call of itself that never stops, and neither a
return nor a ? of a Result or an Option may stand in it (each returns from the function). A call of it then never returns either, so it can end a
block that must leave, as panic can:
import int
fn fail(message: String) -> Never {
panic("config: {message}")
}
fn port(text: String) -> Int {
when let Ok(n) = int.parse(text) else {
fail("'{text}' is not a port")
}
n
}
fn main() {
println(port("8080")) -- 8080
}open in playgroundNever is written only there, as the whole return type of a function
declared with fn (not of a trait’s method): anywhere else in an
annotation it is an error.
A value of type Never is accepted where a value of any type is asked,
and what is taken from it never is either: a call of it, a field read of
it, its ? (which never runs, in any function). A let with a type
annotation gives its names the written type, whatever the value: let port: Int = todo() makes port an Int. So a
stub stands for the value it will be, and the code after it is checked
as for that value:
import string
fn todo() -> Never {
panic("todo")
}
fn port() -> Int {
let port: Int = todo()
println(string.length(port)) -- error: type mismatch: expected String, got Int
port
}
fn main() {
println(port())
}open in playgroundA value that never is decides no type. Where a trait the program
declares, or Number, is asked of its type and nothing else decides
that type, the use is refused: which impl it means is not known. The
help says how to give the value the type it stands for: an annotated
let, let v: Int = todo(), or a stub of that type,
fn todo_int() -> Int { todo() }. silt’s own traits (Display,
Equal, Compare, Hash) ask nothing of such a value.
trait Size {
fn size(self) -> Int
}
trait Size for Int {
fn size(self) -> Int {
self
}
}
fn todo() -> Never {
panic("todo")
}
fn total(x: a) -> Int where a: Size {
Size.size(x)
}
fn main() {
println(total(todo())) -- error: cannot infer the type this use of 'total' needs to implement trait 'Size'
}open in playgroundResult and Option Utilities
println(result.map(Ok(1)) { x -> x + 1 }) -- Ok(2)
println(result.flat_map(Ok(1)) { x -> Ok(x + 1) }) -- Ok(2)
println(result.unwrap_or(Err("x"), 0)) -- 0
println(option.map(Some(1)) { x -> x + 1 }) -- Some(2)
println(option.flat_map(Some(1)) { x -> Some(x + 1) }) -- Some(2)
println(option.unwrap_or(None, 0)) -- 0
result.flat_map is symmetric with option.flat_map — both take a value
and a function that returns a wrapped result, and flatten the nesting.