Files
sweet/packages/fresh/src/error.ts
T
Marvin Hagemeister 815b1940e3 chore: restructure repository into packages/ folder (#3197)
We're having a growing number of packages in this repository. This PR
moves them into a `packages/` directory like it's commonly done in other
projects.
2025-08-06 15:52:45 +02:00

79 lines
2.0 KiB
TypeScript

import { type ErrorStatus, STATUS_TEXT } from "@std/http/status";
export type { ErrorStatus };
/**
* Error that's thrown when a request fails. Correlates to a
* {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status | HTTP status}.
*
* @property status The HTTP status code.
*
* @example Basic usage
* ```ts
* import { App, HttpError } from "fresh";
* import { expect } from "@std/expect";
*
* const app = new App()
* .get("/", () => new Response("ok"))
* .get("/not-found", () => {
* throw new HttpError(404, "Nothing here");
* });
*
* const handler = app.handler();
*
* try {
* await handler(new Request("http://localhost/not-found"))
* } catch (error) {
* expect(error).toBeInstanceOf(HttpError);
* expect(error.status).toBe(404);
* expect(error.message).toBe("Nothing here");
* }
* ```
*/
export class HttpError extends Error {
/**
* The HTTP status code.
*
* @example Basic usage
* ```ts
* import { App, HttpError } from "fresh";
* import { expect } from "@std/expect";
*
* const app = new App()
* .get("/", () => new Response("ok"))
* .get("/not-found", () => {
* throw new HttpError(404, "Nothing here");
* });
*
* const handler = app.handler();
*
* try {
* await handler(new Request("http://localhost/not-found"))
* } catch (error) {
* expect(error).toBeInstanceOf(HttpError);
* expect(error.status).toBe(404);
* expect(error.message).toBe("Nothing here");
* }
* ```
*/
status: ErrorStatus;
/**
* Constructs a new instance.
*
* @param status The HTTP status code.
* @param message The error message. Defaults to the status text of the given
* status code.
* @param options Optional error options.
*/
constructor(
status: ErrorStatus,
message: string = STATUS_TEXT[status],
options?: ErrorOptions,
) {
super(message, options);
this.name = this.constructor.name;
this.status = status;
}
}