Skip to content

Instantly share code, notes, and snippets.

@thelinuxlich
Last active February 23, 2024 19:45
Show Gist options
  • Select an option

  • Save thelinuxlich/3ff3d9bf477b27b41e81f311911cc761 to your computer and use it in GitHub Desktop.

Select an option

Save thelinuxlich/3ff3d9bf477b27b41e81f311911cc761 to your computer and use it in GitHub Desktop.

Revisions

  1. thelinuxlich revised this gist Nov 17, 2023. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion assertHTTP.ts
    Original file line number Diff line number Diff line change
    @@ -30,7 +30,7 @@ export class HTTPError extends Error {
    */
    export function assertHTTP(
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    // biome-ignore lint/suspicious/noExplicitAny: <explanation>
    // biome-ignore lint/suspicious/noExplicitAny: this param accepts *anything* for real
    condition: any,
    message?: string,
    code: ALLOWED_HTTP_STATUS_CODES = '400',
  2. thelinuxlich created this gist Nov 17, 2023.
    46 changes: 46 additions & 0 deletions assertHTTP.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    import { getReasonPhrase } from 'http-status-codes'

    export type ALLOWED_HTTP_STATUS_CODES =
    | '400'
    | '401'
    | '403'
    | '404'
    | '500'
    | '501'
    | '502'
    | '503'
    | '504'
    | '505'

    export class HTTPError extends Error {
    code: ALLOWED_HTTP_STATUS_CODES
    constructor(code: ALLOWED_HTTP_STATUS_CODES, message: string) {
    super(message)
    this.name = getReasonPhrase(code)
    this.code = code
    }
    }
    /**
    * Asserts that a condition is true, otherwise throws an HTTPError with the specified status code and message.
    * @param {any} condition - The condition to assert.
    * @param {string} [message] - The message to include in the error. If not provided, the default HTTP STATUS message will be used.
    * @param {ALLOWED_HTTP_STATUS_CODES} [code='400'] - The HTTP status code to include in the error. Defaults to 400 Bad Request.
    * @returns {void}
    * @throws {HTTPError} Throws an HTTPError if the condition is false.
    */
    export function assertHTTP(
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    // biome-ignore lint/suspicious/noExplicitAny: <explanation>
    condition: any,
    message?: string,
    code: ALLOWED_HTTP_STATUS_CODES = '400',
    ): asserts condition {
    if (condition) return
    const origSTL = Error.stackTraceLimit // a trick for ~3x faster exceptions
    Error.stackTraceLimit = 0
    try {
    throw new HTTPError(code, message || getReasonPhrase(code))
    } finally {
    Error.stackTraceLimit = origSTL
    }
    }