|
1 | 1 | import { STATUS_TEXT } from "@std/http/status"; |
2 | 2 |
|
| 3 | +/** |
| 4 | + * Error that's thrown when a request fails. Correlates to a |
| 5 | + * {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status | HTTP status}. |
| 6 | + * |
| 7 | + * @property status The HTTP status code. |
| 8 | + * |
| 9 | + * @example Basic usage |
| 10 | + * ```ts |
| 11 | + * import { App, HttpError } from "fresh"; |
| 12 | + * import { expect } from "@std/expect"; |
| 13 | + * |
| 14 | + * const app = new App() |
| 15 | + * .get("/", () => new Response("ok")) |
| 16 | + * .get("/not-found", () => { |
| 17 | + * throw new HttpError(404, "Nothing here"); |
| 18 | + * }); |
| 19 | + * |
| 20 | + * const handler = await app.handler(); |
| 21 | + * |
| 22 | + * try { |
| 23 | + * await handler(new Request("http://localhost/not-found")) |
| 24 | + * } catch (error) { |
| 25 | + * expect(error).toBeInstanceOf(HttpError); |
| 26 | + * expect(error.status).toBe(404); |
| 27 | + * expect(error.message).toBe("Nothing here"); |
| 28 | + * } |
| 29 | + * ``` |
| 30 | + */ |
3 | 31 | export class HttpError extends Error { |
| 32 | + /** |
| 33 | + * The HTTP status code. |
| 34 | + * |
| 35 | + * @example Basic usage |
| 36 | + * ```ts |
| 37 | + * import { App, HttpError } from "fresh"; |
| 38 | + * import { expect } from "@std/expect"; |
| 39 | + * |
| 40 | + * const app = new App() |
| 41 | + * .get("/", () => new Response("ok")) |
| 42 | + * .get("/not-found", () => { |
| 43 | + * throw new HttpError(404, "Nothing here"); |
| 44 | + * }); |
| 45 | + * |
| 46 | + * const handler = await app.handler(); |
| 47 | + * |
| 48 | + * try { |
| 49 | + * await handler(new Request("http://localhost/not-found")) |
| 50 | + * } catch (error) { |
| 51 | + * expect(error).toBeInstanceOf(HttpError); |
| 52 | + * expect(error.status).toBe(404); |
| 53 | + * expect(error.message).toBe("Nothing here"); |
| 54 | + * } |
| 55 | + * ``` |
| 56 | + */ |
4 | 57 | status: number; |
5 | 58 |
|
| 59 | + /** |
| 60 | + * Constructs a new instance. |
| 61 | + * |
| 62 | + * @param status The HTTP status code. |
| 63 | + * @param message The error message. Defaults to the status text of the given |
| 64 | + * status code. |
| 65 | + * @param options Optional error options. |
| 66 | + */ |
6 | 67 | constructor( |
7 | 68 | status: keyof typeof STATUS_TEXT, |
8 | 69 | message: string = STATUS_TEXT[status], |
|
0 commit comments