http-exception.ts
This file
Path
src/http-exception.ts
78 lines · 2.3 KiB · TypeScript
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–78why, one step back1/**2 * @module3 * This module provides the `HTTPException` class.4 */56import type { ContentfulStatusCode } from './utils/http-status'78/**9 * Options for creating an `HTTPException`.10 * @property res - Optional response object to use.11 * @property message - Optional custom error message.12 * @property cause - Optional cause of the error.13 */14type HTTPExceptionOptions = {15 res?: Response16 message?: string17 cause?: unknown18}1920/**21 * `HTTPException` must be used when a fatal error such as authentication failure occurs.22 *23 * @see {@link https://hono.dev/docs/api/exception}24 *25 * @param {StatusCode} status - status code of HTTPException26 * @param {HTTPExceptionOptions} options - options of HTTPException27 * @param {HTTPExceptionOptions["res"]} options.res - response of options of HTTPException28 * @param {HTTPExceptionOptions["message"]} options.message - message of options of HTTPException29 * @param {HTTPExceptionOptions["cause"]} options.cause - cause of options of HTTPException30 *31 * @example32 * ```ts33 * import { HTTPException } from 'hono/http-exception'34 *35 * // ...36 *37 * app.post('/auth', async (c, next) => {38 * // authentication39 * if (authorized === false) {40 * throw new HTTPException(401, { message: 'Custom error message' })41 * }42 * await next()43 * })44 * ```45 */46export class HTTPException extends Error {47 readonly res?: Response48 readonly status: ContentfulStatusCode4950 /**51 * Creates an instance of `HTTPException`.52 * @param status - HTTP status code for the exception. Defaults to 500.53 * @param options - Additional options for the exception.54 */55 constructor(status: ContentfulStatusCode = 500, options?: HTTPExceptionOptions) {56 super(options?.message, { cause: options?.cause })57 this.res = options?.res58 this.status = status59 }6061 /**62 * Returns the response object associated with the exception.63 * If a response object is not provided, a new response is created with the error message and status code.64 * @returns The response object.65 */66 getResponse(): Response {67 if (this.res) {68 const newResponse = new Response(this.res.body, {69 status: this.status,70 headers: this.res.headers,71 })72 return newResponse73 }74 return new Response(this.message, {75 status: this.status,76 })77 }78}