betterthrow
v1.0.0-next.5
Published
Define the errors your program can generate, create beautiful unions.
Maintainers
Readme
Betterthrow
Define the errors your program can generate, create beautiful unions. Work in progress.
Setup
Install the library:
npm install betterthrow --saveRecommended tsconfig.json settings:
{
"strict": true,
"exactOptionalPropertyTypes": true,
...
}Example
import { betterthrow, error, group } from "betterthrow";
const HttpError = betterthrow("http")
.context<{
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
pathname: string;
}>()
.errors(
group()
.context<{ username?: string }>()
.data({ source: "client" })
.errors(
error("bad_request")
.context<{ input?: unknown }>()
.data({ status: 400 }),
error("unauthorized").data({ status: 401 }),
error("forbidden").data({ status: 403 }),
error("not_found").data({ status: 404 }),
),
group()
.data({ source: "server" })
.errors(
error("internal_server_error", "Server error").data({ status: 500 }),
error("bad_gateway", "Bad Gateway").data({ status: 502 }),
error("service_unavailable", "Service unavailable").data({
status: 503,
}),
),
)
.messages((err) => `HTTP Error ${err.status} (${err.code})`)
.json((err) => ({
...err.toPlainObject(),
redirectTo: err.status < 500 ? "home_page" : "error_page",
}))
.build();
// Example 1 - Bad Request
const badRequest = new HttpError({
code: "bad_request",
method: "GET",
pathname: "/bad/request",
username: "example",
input: "some junk input",
});
badRequest satisfies {
message: string;
kind: "http";
code: "bad_request";
source: "client";
status: 400;
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
pathname: string;
username?: string;
input?: unknown;
};
// Example 2 - Server Error
const serverError = new HttpError.InternalServerError({
method: "POST",
pathname: "/server/error",
});
serverError satisfies {
message: string;
kind: "http";
code: "internal_server_error";
source: "server";
status: 500;
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
pathname: string;
};