Exception

Throwing HTTP errors with a status attached.

All errors are caught by App.handleError, whatever their type. What an Exception adds is the Status to answer with: it is rendered through Exception.toRes, message and detail intact, while an ordinary error becomes an opaque Status.INTERNAL_SERVER_ERROR so an accidental TypeError does not leak its message to the client.

Throwing one is the intended way to end a request early:

import { Exception, Status } from "@ozanarslan/corpus";

if (!user) throw new Exception("User not found", Status.NOT_FOUND);

Subclass it for errors you raise often, so the status and message live in one place rather than at every throw site.

Contents
  1. Exception

Exception

class

class Exception extends Error

An error carrying the Status it should be answered with.

Beyond a status, an exception can carry Exception.data — either arbitrary detail to include in the error body, or a fully formed Res when the error response needs its own headers or shape.

Exception.constructor()

constructor();
constructor(message: string, status: Status, data?: unknown);
constructor(message?: string, status?: Status, data?: unknown)

Creates an exception for subclasses, which assign Exception.message, Exception.status and Exception.data themselves.

Creates an exception to throw from a handler.

Parameters

Exception.message

override message!: string

Human-readable description, sent to the client in the error body.

Exception.status

status!: Status

The Status the response is sent with.

Exception.data

data?: unknown

Optional detail. An arbitrary value is placed under error in the response body; a Res is used as the response itself.

Exception.toRes()

toRes(): Res

Renders the exception as the response to send.

When Exception.data is a Res, that response is used directly: its status is overwritten with Exception.status, the Exception message gets discarded. Otherwise a fresh Res is built with the message and the detail under error.

Returns — The Res for this error. Called by App.handleError.

Exception.isStatusOf()

isStatusOf(status: Status | keyof typeof Status): boolean

Checks the exception's status, by numeric value or by Status name.

Useful when catching an exception to branch on what went wrong:

if (err instanceof Exception && err.isStatusOf("NOT_FOUND")) { … }

Parameters

Returns — true when Exception.status matches.