Skip to content

Errors as values

parseWebhook from lesson 5 returns a JobEvent. Its type says nothing about the three ways it can fail: an unknown source, text that isn’t JSON, and a body with the wrong shape. A caller who forgets a try gets a crash in the request handler, and the compiler said nothing.

A thrown error is invisible in a function’s type. An error that the code expects, because the sender is a stranger on the internet, should be data that the signature shows. This lesson builds that for Relay.

With strict, the variable in catch (e) is unknown, not any, because JavaScript can throw anything. Narrow it before use:

function describe(e: unknown): string {
if (e instanceof SyntaxError) return `bad JSON: ${e.message}`
if (e instanceof Error) return e.message
return String(e)
}
try {
JSON.parse("{ nope")
} catch (e) {
// @ts-expect-error: 'e' is of type 'unknown'
console.log(e.message)
console.log(describe(e))
}

An error class extends Error, sets name, and passes the original error on as cause so the stack of the real problem isn’t lost:

class InvalidJson extends Error {
readonly source: string
constructor(source: string, cause: unknown) {
super(`${source}: body is not valid JSON`, { cause })
this.name = "InvalidJson"
this.source = source
}
}
try {
JSON.parse("{ nope")
} catch (e) {
const error = new InvalidJson("relay", e)
console.log(error.cause instanceof SyntaxError) // true
}

{ cause } is an ES2022 option on the Error constructor, and the target: "esnext" setting from lesson 1 includes it. The fields are assigned in the constructor body instead of using parameter properties (constructor(readonly source: string)), because Node’s type stripping can’t erase that syntax, and erasableSyntaxOnly rejects it.

Give each class a _tag field with a literal type, as in JobEvent. A union of the classes is then a discriminated union, and switch narrows it:

class UnknownSource extends Error {
readonly _tag = "UnknownSource"
}
class InvalidJson extends Error {
readonly _tag = "InvalidJson"
}
class InvalidPayload extends Error {
readonly _tag = "InvalidPayload"
readonly problem = "missing jobId"
}
type ParseError = UnknownSource | InvalidJson | InvalidPayload
function problemOf(error: ParseError): string {
switch (error._tag) {
case "UnknownSource":
case "InvalidJson":
return error.message
case "InvalidPayload":
return error.problem // narrowed to InvalidPayload
}
}

readonly _tag = "UnknownSource" has the literal type "UnknownSource", not string. Why a tag and not instanceof? Plain object results and errors from another module or worker don’t share a class, and a tag is serializable. It also reads the same as JobEvent.

Two kinds of failure need two treatments:

  • Expected: the outside world sent something wrong. Return it as a value. The caller has to handle it.
  • Bugs: Relay’s own code broke an assumption, such as an index that must exist. These still throw. Nobody can recover them at the call site, and a stack trace is what you want.

If every failure became a value, the signature would list things no caller can act on.

parseBody returns one of two shapes, with a discriminant, ok:

type JobEvent = { readonly _tag: "JobQueued"; readonly jobId: string; readonly at: number }
declare class UnknownSource extends Error {
readonly _tag = "UnknownSource"
}
declare class InvalidJson extends Error {
readonly _tag = "InvalidJson"
}
type ParseError = UnknownSource | InvalidJson
type ParseResult =
| { readonly ok: true; readonly event: JobEvent }
| { readonly ok: false; readonly error: ParseError }
declare function parseBody(source: string, text: string): ParseResult
const result = parseBody("relay", "{}")
// @ts-expect-error: 'event' doesn't exist on the failure shape
result.event
if (result.ok) {
console.log(result.event.jobId)
} else {
console.log(result.error._tag)
}

The caller can’t reach event without checking ok first. Forgetting the failure case is now a compile error.

This shape is written out for one event type. M3 makes it generic so one Result serves every function, and M6 adds map and flatMap so you chain steps without a switch at each one.

Every error kind needs an HTTP status. Make the compiler check that none is missing:

type ParseError =
| { readonly _tag: "UnknownSource" }
| { readonly _tag: "InvalidJson" }
| { readonly _tag: "InvalidPayload" }
const STATUS = {
UnknownSource: 404,
InvalidJson: 400,
InvalidPayload: 422,
} satisfies Record<ParseError["_tag"], number>

ParseError["_tag"] is the union of the tags (an indexed access type, which M3 covers properly). Add a fourth error and STATUS stops compiling until it has a number. Remove a key and it fails too.

The other way is a switch that ends with absurd, from lesson 2:

type ParseError =
| { readonly _tag: "UnknownSource" }
| { readonly _tag: "InvalidJson" }
| { readonly _tag: "InvalidPayload" }
const absurd = (x: never): never => {
throw new Error(`unhandled: ${JSON.stringify(x)}`)
}
function statusOf(error: ParseError): number {
switch (error._tag) {
case "UnknownSource":
return 404
case "InvalidJson":
return 400
default:
// @ts-expect-error: 'InvalidPayload' isn't assignable to 'never'
return absurd(error)
}
}

The table is shorter. The switch is better when a case does more than return a number.

The starter’s classes are almost right, but InvalidPayload has no _tag, parseBody throws instead of returning, and statusOf has no InvalidPayload case. Fix the classes, return every failure as a value, and make statusOf exhaustive. parseBody must never throw.

  • catch (e) is unknown. Narrow with instanceof before you read it.
  • An error class sets name, keeps the original in { cause }, and carries a literal _tag.
  • Expected failures are values in the return type. Bugs still throw.
  • A result union with an ok discriminant forces the caller to handle failure.
  • satisfies Record<E["_tag"], ...> or a switch with absurd makes the compiler check every error has a status.