Skip to content

Accumulating error unions

Relay’s handleJob can fail three ways. The payload may be garbage, the notifier may answer 503, and the queue may be down when it is time to acknowledge. In the first version all three became throw new Error("job failed"). The HTTP layer returned 500 for every one, so a client that sent a bad payload retried it forever.

Errors as values already fixed half of this. Here we make the error type of each function follow from the functions it calls, so the type says exactly what can go wrong and the compiler tells you which cases are still unhandled.

Give every error class a literal _tag. The classes become a discriminated union, and instanceof still works for callers who prefer it:

class InvalidPayload extends Error {
readonly _tag = "InvalidPayload"
}
class NotifyFailed extends Error {
readonly _tag = "NotifyFailed"
constructor(readonly status: number) {
super(`notify failed: ${status}`)
}
}
class QueueUnavailable extends Error {
readonly _tag = "QueueUnavailable"
}
function describe(e: InvalidPayload | NotifyFailed | QueueUnavailable): string {
switch (e._tag) {
case "NotifyFailed":
return `upstream said ${e.status}`
case "InvalidPayload":
return "bad payload"
case "QueueUnavailable":
return "queue down"
}
}

Inside the NotifyFailed case e.status exists. In the others it would not. That is the same narrowing you already use for unions.

The error type is the union of the callees’ errors

Section titled “The error type is the union of the callees’ errors”

When handleJob calls three steps, its failures are the union of theirs. Write that union in the return type:

class InvalidPayload extends Error {
readonly _tag = "InvalidPayload"
}
class NotifyFailed extends Error {
readonly _tag = "NotifyFailed"
constructor(readonly status: number) {
super(`notify failed: ${status}`)
}
}
class QueueUnavailable extends Error {
readonly _tag = "QueueUnavailable"
}
type Result<A, E> =
| { readonly ok: true; readonly value: A }
| { readonly ok: false; readonly error: E }
declare function parse(payload: string): Result<string, InvalidPayload>
declare function notify(text: string): Promise<Result<void, NotifyFailed>>
declare function ack(id: string): Promise<Result<void, QueueUnavailable>>
async function handleJob(
id: string,
payload: string,
): Promise<Result<void, InvalidPayload | NotifyFailed | QueueUnavailable>> {
const parsed = parse(payload)
if (!parsed.ok) return parsed
const sent = await notify(parsed.value)
if (!sent.ok) return sent
return ack(id)
}

return parsed works because a Result<string, InvalidPayload> that is not ok is already a Result<never, InvalidPayload>, which fits the wider return type. The signature is the documentation: a caller sees all three failures without reading the body. If ack later gains a new error, handleJob stops compiling until you add it.

A layer that deals with a failure should remove it from the type. Exclude does that on a union (distributive conditional types):

class InvalidPayload extends Error {
readonly _tag = "InvalidPayload"
}
class NotifyFailed extends Error {
readonly _tag = "NotifyFailed"
constructor(readonly status: number) {
super(`notify failed: ${status}`)
}
}
class QueueUnavailable extends Error {
readonly _tag = "QueueUnavailable"
}
class Requeue extends Error {
readonly _tag = "Requeue"
}
type Result<A, E> =
| { readonly ok: true; readonly value: A }
| { readonly ok: false; readonly error: E }
type HandleError = InvalidPayload | NotifyFailed | QueueUnavailable
type Without<E, Tag extends string> = Exclude<E, { _tag: Tag }>
async function recoverNotify(
run: () => Promise<Result<void, HandleError>>,
): Promise<Result<void, Without<HandleError, "NotifyFailed"> | Requeue>> {
const result = await run()
if (result.ok) return result
const e = result.error
if (e._tag !== "NotifyFailed") return { ok: false, error: e }
return { ok: false, error: new Requeue(`notify ${e.status}`) }
}

After the if, e is NotifyFailed and the compiler accepts the Requeue. The return type says it too: NotifyFailed is gone, Requeue is new. A caller of recoverNotify can no longer write a branch for NotifyFailed, and does not need one.

Map infrastructure errors at a layer boundary

Section titled “Map infrastructure errors at a layer boundary”

NotifyFailed carries an HTTP status. That is a detail of one provider. Code above the layer should see domain errors only. Convert at the boundary, and keep the original as the cause when the detail matters for debugging:

class NotifyFailed extends Error {
readonly _tag = "NotifyFailed"
constructor(readonly status: number) {
super(`notify failed: ${status}`)
}
}
class InvalidPayload extends Error {
readonly _tag = "InvalidPayload"
}
function fromNotify(e: NotifyFailed): InvalidPayload | undefined {
// A 4xx means upstream rejected our message. Retrying the same bytes will not help.
return e.status < 500 ? new InvalidPayload(`rejected ${e.status}`, { cause: e }) : undefined
}

In Relay, a 4xx from the notifier is the job’s fault, so it becomes InvalidPayload, while a 5xx is the notifier’s fault and is retried. The mapping lives in one place instead of in every caller.

At the edge of the program every remaining error must become something concrete. A switch with a never check makes sure none is forgotten:

class InvalidPayload extends Error {
readonly _tag = "InvalidPayload"
}
class QueueUnavailable extends Error {
readonly _tag = "QueueUnavailable"
}
class Requeue extends Error {
readonly _tag = "Requeue"
}
type AppError = InvalidPayload | QueueUnavailable | Requeue
function toHttpStatus(e: AppError): number {
switch (e._tag) {
case "InvalidPayload":
return 422
case "QueueUnavailable":
return 503
case "Requeue":
return 202
default: {
const unreachable: never = e
return unreachable
}
}
}

Add a fourth error class to AppError and const unreachable: never = e fails to compile, pointing at the one function that needs a decision. This is how Relay stopped answering 500 for everything.

Write the three pieces that complete Relay’s job handling. handleJob parses, notifies and acknowledges, in that order. recoverNotify retries a failing notification and changes the error type, and toHttpStatus is the exhaustive end of the chain. The starter’s handleJob does nothing, recoverNotify is too loose, and toHttpStatus returns 500 for everything.

  • Tag every error class with a literal _tag. It makes the classes a discriminated union.
  • A function’s error type is the union of its callees’ errors, written in its return type.
  • Handling a case removes it from the type: Exclude<E, { _tag: "X" }> on the way out.
  • Map infrastructure errors to domain errors at a layer boundary, once.
  • End with a switch on _tag and a never check so a new error is a compile error.
  • Narrowing: discriminated unions and exhaustiveness checking.