# Errors

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

```go
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
}
```

```js
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:

```go
const name, err = find(id)
if err != null {
    return "", error("load user", err)  // "load user: no user 7"
}
```

```js
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.

```go
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, err` needs an error that is not null: `return null, null` is an error, and so is an
  `err` that has not been checked.
- After `const user, err = loadUser(id)` the value has the type `?User`; once `err` is found to be
  `null` (`if err != null { return }`, `if err == null { ... }`), it is a `User`. This works for
  `const` only: variables of `let` may be assigned apart. With `const user, _ = ...` the value
  stays `?User`.
- Where the value may be `null` without 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 return `null, err` as well as `0, err`.
- Nothing changes at runtime. In the `.d.ts` the result is `[User, null] | [null, Error]`, which
  TypeScript narrows the same way.

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

```go
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.

```go
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
```

```js
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 a `try { }` around it
  would: `try JSON.parse(readFileSync(path, "utf8"))` catches the errors of both calls. With
  `await` in it, a rejected Promise as well: `try await fetch(url)`. A thrown value that is not an
  `Error`, `throw "empty"`, becomes `new Error("empty")`.
- **What it gives:** `(T, error)` for an expression of type `T`, and the value is `null` with an
  error, as in "A value or an error": `config` may be `null` until `parseErr` is checked. An
  expression that gives nothing, or only an `error`, 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:** `try` takes the whole expression after it, as `return` does, 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. So `yield` of an iterator cannot be inside `try`.

### decode

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

```go
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
```

```js
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 type `unknown` or `any`, such as `JSON.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 `?string` is checked for `null` first.
- **What it gives:** the value itself, as it is, when it fits: fields that `T` does not have stay in
  it, and nothing is copied. A field of `T` that is missing is an error, unless it is nullable
  (`boss ?User`) or `any`. 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" }`
  of `Circle | Square` gives `r: expected number, got "2"`, and `{ kind: "square" }` gives
  `side: 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 a `func` is the type of each call, as for `make(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. With `rook build --no-check`, without the types, `decode` parses a string and
  checks nothing.
- `decode` is a name elsewhere, as `topic` is: 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.

