Rook
РусскийRU

Errors and defer

Ordinary errors need no exceptions: a function returns an error as its second value, and the caller checks it. An error is made with error("..."). With an error, a function of (Person, error) may return null in place of the value: until err is checked the value may be null, after the check it is not. Where the value may be null without an error too, the result is (?Person, error). error("load", err) wraps an error, as %w does in Go: the message ends with that of err, and cause is err itself. The board can use this result to report a rejected operation to its caller, which then decides how to present the failure.

// An error is the second result, as in Go
func parseAge(text string) (number, error) {
    const age = Number(text)
    if isNaN(age) || age < 0 {
        return 0, error(`"${text}" is not an age`)
    }
    return age, null
}

class Person {
    name string
    age number

    constructor(name string, age number) {
        this.name = name
        this.age = age
    }
}

// A class has no zero value: null goes together with an error
func parsePerson(line string) (Person, error) {
    const parts = line.split(" ")
    const age, err = parseAge(parts[1])
    if err != null {
        return null, error(`"${line}"`, err) // wraps it: its message ends with that of err
    }
    return new Person(parts[0], age), null
}

for line in ["Ann 42", "Bob forty-two"] {
    const person, err = parsePerson(line)
    if err != null {
        console.log("error:", err.message)
        continue
    }
    console.log(person.name, "is", person.age) // err is null, so person is not
}

Exceptions from JS code are caught with try / catch. defer postpones a call until the function exits, which is handy for cleaning up: the call runs after a return and after an exception alike.

// defer runs a call when the function exits, even after return or an exception
func report(title string) {
    console.log("start:", title)
    defer console.log("end:", title)
    console.log("working…")
}

report("report")

// try / catch catches exceptions from JS code
func parseJson(text string) (any, error) {
    try {
        return JSON.parse(text), null
    } catch e {
        return null, error(e.message)
    }
}

const _, err = parseJson("{ not json }")
if err != null {
    console.log("could not parse:", err.message)
}