Appearance
Errors
Errors are values, as in Go and Zig. A function's type says how it can fail, and the caller handles every failure or passes it on. Nothing is thrown, and nothing can fail behind your back.
Bugs are different. An index out of range or a ! on null is a panic, which no ordinary code handles (below).
A function that can fail
fail ends a function with an error, as return ends it with a value:
lib/ports.weft
weft
type PortError = NotANumber { text: string } | OutOfRange { port: number }
export fn checkPort(n: number): number ! PortError {
if !n.isInteger() { fail NotANumber { text: `${n}` } }
if n < 1 || n > 65535 { fail OutOfRange { port: n } }
return n
}number ! PortError is the result type: a number, or a PortError. You can leave the ! PortError out, and the compiler infers it from what the body fails with and what its trys pass on. A function that does neither can't fail. Write : number ! never to say a function must not fail; the compiler then rejects a fail in it.
An error is ordinary data, usually a type with variants (Types). It can be compared with ==, converted to json, sent over the network and matched.
Matching errors
A caller that wants to know what went wrong matches the error. match must cover every variant, so adding a variant to PortError shows you every place that needs to handle it:
weft
type PortError = NotANumber { text: string } | OutOfRange { port: number }
fn explain(e: PortError): string {
return match e {
NotANumber { text } => `"${text}" isn't a whole number`,
OutOfRange { port } => `${port} isn't between 1 and 65535`,
}
}The standard library's modules define their errors the same way: std/math's ParseError { input }, std/json's SyntaxError { message, at }, std/db's DbError, std/http's NetworkError { message, status? }. You import one by name to write it or match it (import type { ParseError } from "std/math"); an error you only pass along needs no import.
Passing an error on: try
A call that can fail must go through try. Plain try passes the error to your own caller: on an error, the enclosing function fails with it, and its error type grows to include it.
lib/config.weft
weft
import { parse } from "std/json"
type Config = { name: string, port: number }
export fn readConfig(text: string): Config {
let j = try parse(text)
return try j as Config
}readConfig fails with parse's SyntaxError or the cast's CastError, and its type says so: Config ! SyntaxError | CastError. Leaving out a try is an error that names what the call can fail with:
rejected by the compiler (E2030)
weft
import { parseNumber } from "std/math"
export fn double(text: string): number {
let n = parseNumber(text)
return n * 2
}try goes anywhere an expression goes: foo(try bar()), return try load(id). Writing try before something that can't fail is a warning.
Handling it: two bindings
let value, err = try f() never fails. err is the error, or null; value is the result when err is null. After a check that leaves when there is an error, value has the result's type:
lib/ports.weft
weft
import { parseNumber } from "std/math"
type PortError = NotANumber { text: string } | OutOfRange { port: number }
fn parsePort(text: string): number ! PortError {
let n = try parseNumber(text) else e => fail NotANumber { text: e.input }
if !n.isInteger() || n < 1 || n > 65535 { fail OutOfRange { port: n } }
return n
}
export fn describe(text: string): string {
let port, err = try parsePort(text)
if err != null {
return match err {
NotANumber { text } => `"${text}" isn't a number`,
OutOfRange { port } => `${port} is out of range`,
}
}
return `listening on ${port}`
}port is a number? until the if, and a number after it. Either name can be _ when you don't need it.
A fallback: try … else
try f() else x gives x when f() fails. else e => … can use the error. Neither form fails:
weft
import { parseNumber } from "std/math"
import type { ParseError } from "std/math"
import { warn } from "std/log"
export fn pageSize(text: string): number {
return try parseNumber(text) else 20
}
fn defaultLimit(e: ParseError): number {
warn(`not a number: "${e.input}"`)
return 100
}
export fn limit(text: string): number {
return try parseNumber(text) else e => defaultLimit(e)
}The fallback is an expression, and it extends as far right as an expression does. It can also fail, with an error of your own that says what was being read:
weft
import { parseNumber } from "std/math"
type SettingsError = BadVolume { text: string }
export fn volume(text: string): number ! SettingsError {
return try parseNumber(text) else e => fail BadVolume { text: e.input }
}fail is an expression
fail e has the type never, so it fits wherever a value goes. With ?? it turns a missing value into an error:
weft
type User = { id: string, name: string }
type LookupError = NotFound { id: string }
let users = Map<string, User>()
export fn nameOf(id: string): string ! LookupError {
let user = users.get(id) ?? fail NotFound { id }
return user.name
}A function whose every path fails returns never, so try alwaysFails() else x has the type of x.
Cleaning up: defer
defer runs a statement, or a block, when the enclosing block ends, however it ends: normally, by return, break, continue, fail, or a try passing an error on. Write the cleanup next to the setup:
Notes.weft
weft
import { uuid } from "std/random"
type Note = { id: string, text: string }
let mut notes: Note[] = []
let mut draft = ""
let mut problem = ""
let mut saving = false
action fn save(text: string): Note {
return Note { id: uuid(), text }
}
async fn add() {
saving = true
defer saving = false
let note, err = try await save(draft)
if err != null {
problem = err.message
return
}
notes.push(note)
draft = ""
}
---
<TextField bind:value={draft} onsubmit={add} disabled={saving} />
<Text>{problem}</Text>saving goes back to false on both ways out: the early return and the end of the function. Several defers run last first. In a loop, a body's defer runs at the end of each iteration:
weft
import { parseNumber } from "std/math"
import { log } from "std/log"
export fn sum(lines: string[]): number {
let mut total = 0
for line of lines {
defer log(`read ${line}`)
total += try parseNumber(line)
}
return total
}A defer reads variables as they are when it runs. A return's value is computed before the defers run. The body of a defer can't leave it (return, fail, a passing try) or await, so it handles its own errors (try … else). A panic skips the defers that haven't run.
Casting with as
j as T checks a json value against a type when the program runs. It can fail, with a CastError { path, expected }: the path of the field that didn't fit, starting at value, and the type expected there.
weft
type Person = { name: string, age: number }
type Team = { people: Person[] }
export fn check(j: json): string {
let team, err = try j as Team
if err != null {
return `${err.path} should be ${err.expected}`
}
return `${team.people.length} people`
}For { "people": [{ "name": "Ana", "age": 30 }, { "name": "Bo" }] }, check returns "value.people[1].age should be number". A cast the compiler can prove, such as a Person as a record with fewer fields, can't fail and needs no try.
Tasks
Calling an async function that can fail doesn't fail: it gives a task. The await is what fails, so it takes the try:
weft
import { parse } from "std/json"
import { sleep } from "std/time"
type Page = { title: string }
async fn load(text: string): Page {
await sleep(1)
let j = try parse(text)
return try j as Page
}
export async fn loadAll(texts: string[]): Page[] {
let tasks = texts.map(t => load(t))
return try await Task.all(tasks)
}
export async fn titleOf(text: string): string {
let page = try await load(text) else Page { title: "Untitled" }
return page.title
}Task.all fails with the first task that fails. A task's error that nothing ever awaits is reported when the work queue runs dry, so it isn't lost.
An async derived value (derived x = await …) keeps its error in x.error, and markup's @await shows it in its @catch (Components).
Across the network
A server function's errors reach the client as data, typed. Seen from the client, save below gives a Task<Note ! SaveError | NetworkError>: its own errors, plus std/http's NetworkError for a call that failed on the way (no connection, or the server answering 500):
Composer.weft
weft
import { uuid } from "std/random"
import type { NetworkError } from "std/http"
type Note = { id: string, text: string }
type SaveError = Empty | TooLong { max: number }
let mut draft = ""
let mut problem = ""
action fn save(text: string): Note ! SaveError {
let t = text.trim()
if t == "" { fail Empty }
if t.length > 500 { fail TooLong { max: 500 } }
return Note { id: uuid(), text: t }
}
async fn send() {
let _, err = try await save(draft)
problem = match err {
null => "",
Empty => "Write something first.",
TooLong { max } => `At most ${max} characters.`,
NetworkError { status } => status == null ? "You're offline." : "The server had a problem.",
}
if err == null { draft = "" }
}
---
<TextField bind:value={draft} onsubmit={send} />
<Text>{problem}</Text>On the server, an HTTP handler may fail with any error: the request is answered with a 500 and the error is printed. std/auth's AuthError is the exception: Unauthorized answers 401, Forbidden 403 and RateLimited 429, so passing it on is how a guard works:
server/main.weft
weft
import { router, json, serve } from "std/http"
import { requireRole } from "std/auth"
let api = router()
.get("/stats", async req => {
let user = try await requireRole(req, "admin")
return json({ by: user.id, count: 3 })
})
try await serve({ port: 8080 }, api)A module's top level can pass errors on too: the module fails to load, and so does every module that imports it. weft run prints the error and exits with code 1, which is what try await serve(…) above does when the port is taken.
Callbacks that fail
A list method that runs your callback during the call fails when the callback fails. map stops at the first error, and the call fails with it:
weft
import { parseNumber } from "std/math"
export fn total(fields: string[]): number {
let numbers = try fields.map(s => try parseNumber(s))
return numbers.sum()
}
export fn totalOrZero(fields: string[]): number {
return try total(fields) else 0
}With a callback that can't fail, map can't either, and needs no try. Your own functions get the same behaviour with an error type parameter:
weft
export fn retry<T, E>(times: number, f: () => T ! E): T ! E {
for _ of 1..times {
let value, err = try f()
if err == null { return value }
}
return try f()
}E is whatever f fails with, and never for a callback that can't fail. Callbacks that run later (timers, event handlers, then) can't fail: there is no caller left to take the error.
Where errors can't go
Passing an error on needs a caller to take it. An event handler, an effect, a component's top level and markup have none, so there every error is handled where it occurs, with two bindings or else. A function that can fail can't be a handler either:
Volume.weftrejected by the compiler (E2029)
weft
import { parseNumber } from "std/math"
let mut text = "5"
let mut volume = 5
fn apply() {
volume = try parseNumber(text)
}
---
<TextField bind:value={text} onsubmit={apply} />The compiler points at the try inside apply and says to handle the error there, for example with volume = try parseNumber(text) else volume. A try that passes an error on, written directly in a handler or an effect, is an error of its own (E4012).
Panics are bugs
A panic is a mistake in the program, not something its caller should handle: an index out of range, ! on null, toFixed(25), a range step of 0, two @for items with one key. A panic is { name, message } (RangeError, TypeError, …). It ends the turn, keeps the writes made before it, and is reported. Code can't raise one, and ordinary code can't catch one.
A panic that nothing shows is printed with where it started:
text
panic RangeError: index 5 is outside the list (length 2)
at inner (lib/util.weft:2)
at outer (lib/util.weft:5)
at main.weft:3Three places see panics:
- In markup,
@try { … } @catch e { … }shows its@catchwhen what's inside panics while rendering. An app'serror.weftdoes the same for a whole page. - The server answers a request that panicked with a 500, which a client's call sees as a
NetworkError. - Tests:
assertPanics(f, name?)checks thatfpanics. A failed assertion is a panic namedAssertionError.
Price.weft
weft
type Row = { name: string, price: number }
prop rows: Row[] = []
prop pick = 0
---
@try {
<Text>{rows[pick].name}: {rows[pick].price.toFixed(2)}</Text>
} @catch e {
<Text>Can't show this row ({e.name}).</Text>
}lib/prices.weft
weft
import { parseNumber } from "std/math"
import { assertEq, assertPanics } from "std/testing"
test "prices parse" {
assertEq(try parseNumber(" 4.5 "), 4.5)
assertPanics(() => { (4.5).toFixed(25) }, "RangeError")
}A test's body may pass errors on: a test whose body fails reports the error and fails.
Why there is no throw
With exceptions, any call might leave the function early, and nothing in the text says which. Weft puts every failure a caller should handle in the type, and every place that handles one is marked with try. Reading a function tells you where it can stop and why.
What remains are bugs. A caller can't do anything sensible about an index out of range in code it called, so a panic doesn't pretend it can: it stops the turn, and the boundaries above (@try, the server, tests) report it.
Running out of fuel or memory is neither: it is a stop (Limits).
| TypeScript | Weft |
|---|---|
throw new Error("…") | fail NotFound { id }, a value of the function's error type |
try { a() } catch (e) { … } around a call | let v, err = try a(), or try a() else fallback |
| letting an exception propagate | try a() |
finally { … } | defer … |
JSON.parse(s) as User (unchecked) | try parse(s), then try j as User (checked) |
a TypeError from a bug | a panic, seen by @try, the server's 500 and assertPanics |