Skip to content
Weaverv0.5.0

Errors

Weaver has no exceptions. A function that can fail says so in its type, and every place where an error can leave a function is marked.

fn f(): T ! E returns a T, or fails with an E. After a call, ! takes the value, or leaves the current function with the error:

import weaver.io.print
fn total(texts: String[]): Int ! {
var sum = 0
for t in texts { sum += Int.parse(t)! }
return sum
}
fn main() ! {
print("${total(["1", "2", "3"])!}")
print("${total(["1", "two"])!}")
}
6
main: not an integer

An error that leaves main is printed, and the program exits with code 1. : Int !, with no type after the !, lets the compiler collect the errors the body can raise; a public function names them.

An error is an enum. #Error writes its messages from the tags after each variant, and fail fails with one:

import weaver.io.print
#Error
enum AgeError =
| Negative(age: Int) `error("an age cannot be negative: ${age}")`
| Unlikely(age: Int) `error("${age} is not a likely age")`
fn checkAge(age: Int): Int ! AgeError {
if age < 0 { fail Negative(age) }
if age > 150 { fail Unlikely(age) }
return age
}
fn main() ! AgeError {
print("${checkAge(36)!}")
print("${checkAge(-1)!}")
}
36
main: an age cannot be negative: -1

Errors compose: fn load(): Config ! IoError | ParseError fails with either, without a wrapping type.

catch handles the error on the spot, with patterns, and gives a value instead:

import weaver.io.print
fn port(text: String): Int = Int.parse(text) catch _ => 8080
fn main() {
print("${port("443")}")
print("${port("https")}")
}
443
8080

A catch that handles only some errors lets the others through, with a final !. A result cannot be ignored: calling a function that can fail without ! or catch is a compile error, and val _ = f() drops its result on purpose.

.context("…") adds what the program was doing to an error, keeping the original as its cause:

fn readPort(text: String): Int ! = Int.parse(text).context("reading the port")!
fn main() ! {
val _ = readPort("80a")!
}
main: reading the port: not an integer

panic("…") is for bugs: a broken invariant, a state that cannot happen. An index out of bounds or an integer overflow are panics too. A panic is not an error to handle: it stops the program, with exit code 101, after releasing its resources.