Errors
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
return null, errneeds an error that is not null:return null, nullis an error, and so is anerrthat has not been checked.- After
const user, err = loadUser(id)the value has the type?User; onceerris found to benull(if err != null { return },if err == null { ... }), it is aUser. This works forconstonly: variables ofletmay be assigned apart. Withconst user, _ = ...the value stays?User. - Where the value may be
nullwithout an error too, the result is nullable:(?User, error), and the value is checked by itself. - The same holds for several values,
(A, B, error), and for numbers and strings:(number, error)may returnnull, erras well as0, err. - Nothing changes at runtime. In the
.d.tsthe result is[User, null] | [null, Error], which TypeScript narrows the same way.
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.
- What it catches: everything thrown in the expression after
try, as atry { }around it would:try JSON.parse(readFileSync(path, "utf8"))catches the errors of both calls. Withawaitin it, a rejected Promise as well:try await fetch(url). A thrown value that is not anError,throw "empty", becomesnew Error("empty"). - What it gives:
(T, error)for an expression of typeT, and the value isnullwith an error, as in "A value or an error":configmay benulluntilparseErris checked. An expression that gives nothing, or only anerror, gives the error alone. Of(User, error)it gives the same(User, error): an exception is one more way to get the error. After several values without an error, the error is added. - Where:
trytakes the whole expression after it, asreturndoes, and gives values to unpack, so it stands where a call with several results does:const v, err = try ...,v, err = try ...,return try .... As a statement it would drop the error, which is a compile error:try { } catch e { }is for blocks of code. - In JS the expression is a function that the runtime calls inside
try/catch, and an async one if the expression waits. Soyieldof an iterator cannot be insidetry.
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.
- What it takes: JSON text, if the argument is a
string: it is parsed, then checked; or a value from JS with typeunknownorany, such asJSON.parse(s): it is only checked.decode<number>(params.get("page") ?? "1")reads a number from the text. Other types are an error, since their values are checked already; a?stringis checked fornullfirst. - What it gives: the value itself, as it is, when it fits: fields that
Tdoes not have stay in it, and nothing is copied. A field ofTthat is missing is an error, unless it is nullable (boss ?User) orany. Only the own fields of an object count. - The error says where the value does not fit:
decode User: tags[1]: expected string, got 42,decode User: name: missing,decode User: invalid JSON: .... Of a union, the member that the value fits deepest is reported, and of those the one whose tag fits:{ kind: "circle", r: "2" }ofCircle | Squaregivesr: expected number, got "2", and{ kind: "square" }givesside: missing. A tag that fits no member gives all of them:kind: expected "circle" | "square", got "oval". - Which types: what JSON holds:
number,string,bool, literal types,?T, arrays, unions, interfaces and object types without methods, generic ones with their arguments (Box<number>), and types that refer to themselves (interface Tree { children Tree[] }). A class,Date,Map,bigint,byte[], a function or a channel is a compile error that says what to decode instead. A type parameter of afuncis the type of each call, as formake(T)(section 3, "make"); one of a class or a method is an error. - An object type is a constant of the module,
$$typeUser, so the fields of each call are not written again. Withrook build --no-check, without the types,decodeparses a string and checks nothing. decodeis a name elsewhere, astopicis: it decodes only before<T>(.
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.