Errors

Rook — 1.0 specification

Expected errors (wrong input, a file not found) are returned as the last value, of type error:

func parsePort(s string) (number, error) {
    const n = Number(s)
    if Number.isNaN(n) || n < 1 || n > 65535 {
        return 0, error(`invalid port: ${s}`)
    }
    return n, null
}

const port, err = parsePort(input)
if err != null {
    console.error(err.message)       // inside the if, err is an Error, not null
}
function parsePort(s) {
  const n = Number(s)
  if (Number.isNaN(n) || n < 1 || n > 65535) {
    return [0, new Error(`invalid port: ${s}`)]
  }
  return [n, null]
}

const [port, err] = parsePort(input)
if (err != null) {
  console.error(err.message)
}

error(msg) creates new Error(msg). error(msg, err) wraps an error, as fmt.Errorf("%w") does in Go: its message ends with that of err, and cause is err itself:

const name, err = find(id)
if err != null {
    return "", error("load user", err)  // "load user: no user 7"
}
return ['', $$wrap('load user', err)] // new Error("load user: no user 7", { cause: err })

The error to wrap cannot be null: it is checked first, as here. An exception caught with catch e, which is any, is wrapped too, and a value that is not an Error gives its text.

Errors created by the Rook runtime have a RookError, RookTypeError, or RookRangeError label. For example, an out-of-range conversion throws a RookRangeError: value is outside the range of int32. In JavaScript, import RookError from rooklang/runtime to test for all three with err instanceof RookError. The specific categories also satisfy instanceof TypeError or instanceof RangeError, respectively. Rook preserves these categories and the stack when it sends an error between workers. Program errors created with error(...) and JavaScript exceptions keep their own categories.

A value or an error

Together with an error, a function may return null in place of any value before it: a class has no zero value, and (User, error) says that the value is null only when there is an error.

func loadUser(id number) (User, error) {
    const data, err = readFile(`users/${id}.json`)
    if err != null {
        return null, err             // err is an Error here, not null
    }
    return new User(JSON.parse(data)), null
}

const user, err = loadUser(id)
console.log(user.name)               // error: "user" may be null until "err" is checked
if err != null {
    return
}
console.log(user.name)               // err is null, so user is a User

Exceptions remain for JS code that throws and for real emergencies:

let config any
try {
    config = JSON.parse(text)
} catch e {
    console.error("bad config:", e)
} finally {
    console.log("done")
}

throw error("unreachable")

catch is written without parentheses, and e has the type any.

try

Experimental: may change between releases; see the status at the top.

import { readFileSync, writeFileSync } from "node:fs"

const text, err = try readFileSync("config.json", "utf8")
if err != null {
    console.error("no config:", err.message)
    return
}
const config, parseErr = try JSON.parse(text)
const response, fetchErr = try await fetch(url)
const saveErr = try writeFileSync("out.txt", text)  // it gives nothing, so only the error
const [text, err] = $$catch(() => readFileSync('config.json', 'utf8'))
// ...
const [config, parseErr] = $$catch(() => JSON.parse(text))
const [response, fetchErr] = await $$catchAsync(async () => await fetch(url))
const saveErr = $$catch(() => writeFileSync('out.txt', text), 0)

JS code reports errors by throwing them; try expr turns what the expression throws into the error of (T, error), the way Rook code returns errors.

decode

Experimental: may change between releases; see the status at the top.

interface User {
    name string
    age number
    role "admin" | "user"
    boss ?User                       // may be missing or null
}

const user, err = decode<User>(await request.text())
if err != null {
    console.error(err.message)       // decode User: age: expected number, got "42"
    return
}
console.log(user.name)               // err is null, so user is a User
const $$typeUser = $$type('User', () => ({
  name: 'string',
  age: 'number',
  role: { literal: ['admin', 'user'] },
  boss: { nullable: $$typeUser },
}))

const [user, err] = $$decodeJson(await request.text(), $$typeUser)

The types are erased, so a value from outside, the body of a request or a file, has the type that the program says it has, and nothing checks it. decode<T>(x) checks it when the program runs: the compiler writes the type T into the JS as data, and the runtime checks the value against it. The result is (T, error), as in section 7: user may be null until err is checked.

unknown is the type of a value that needs checking. JSON.parse returns it, and unknown in TypeScript declarations keeps that type in Rook. Any value fits unknown. To access a member, call the value or assign it to a narrower type, use a check such as typeof value == "string" or decode<T>(value). An explicit assertion as T is erased by the compiler.

Markdown source on GitHub