Standard Error Creation in TypeScript
pnpm add @cluesurf/kink
yarn add @cluesurf/kink
npm i @cluesurf/kink
import { KinkBase, type Take } from '@cluesurf/kink'
const host = '@cluesurf/kink'
type Base = {
syntax_error: {
take: {
line: number
}
}
record_missing: {
take: {
id: string
}
}
}
type Name = keyof Base
const kinkBase = new KinkBase<Base>({
host,
makeCode: (code: number) => code.toString(16).padStart(4, '0'),
// Status used by any form below that does not name its own.
mark: 500,
})
kinkBase.form('syntax_error', take => ({
code: 1,
link: take,
note: 'Syntax error',
}))
kinkBase.form('record_missing', take => ({
code: 2,
link: take,
mark: 404,
note: 'Record not found',
}))
const ERROR = kinkBase.make()
export default function kink<N extends Name>(
form: N,
take?: Take<Base, N>,
) {
return ERROR(form, take)
}import kink from './example.js'
try {
throw kink('syntax_error', { line: 12 })
} catch (e) {
console.log(e)
}Every error carries an optional mark, the HTTP status a server
should answer with when the error reaches a request handler. It
resolves in this order, first one wins:
- the
markpassed at the throw site, - the
markreturned by the form's hook, - the
markgiven to theKinkBaseconstructor.
When none of the three is set, mark stays undefined and the
handler picks the status.
// 404, from the form definition.
throw ERROR('record_missing', { id })
// 410 this one time, overriding the form.
throw ERROR('record_missing', { id }, undefined, 410)The third argument is the original error being wrapped, kept on
the new error as base.
A KinkList takes the highest mark among its members, so
answering with the list's status never reports something milder
than one of the errors inside deserved.
MIT
Made by ClueSurf, meditating on the universe ¤. Follow the work on YouTube, X, Instagram, Substack, Facebook, and LinkedIn, and browse more of our open-source work here on GitHub.