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
Exception
class
class Exception extends ErrorAn 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
message— Human-readable description. It is sent to the client, so write it for whoever receives the response.status— The Status to answer with.data— Optional detail attached to the response body undererror, such as validation failures. Pass aResinstead to control the whole error response — see Exception.toRes.
Exception.message
override message!: stringHuman-readable description, sent to the client in the error body.
Exception.status
status!: StatusThe Status the response is sent with.
Exception.data
data?: unknownOptional detail. An arbitrary value is placed under error in the response body; a Res is used as the response itself.
Exception.toRes()
toRes(): ResRenders 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): booleanChecks 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
status— A Status value or one of its keys.
Returns — true when Exception.status matches.