betterthrow
Version:
Define the errors your program can generate, create beautiful unions.
110 lines (95 loc) • 2.76 kB
Markdown
<p>
<a href="https://github.com/traverse1984/betterthrow/actions?query=branch%3Adevelopment">
<img src="https://github.com/traverse1984/betterthrow/actions/workflows/test.yml/badge.svg?event=push&branch=main" alt="betterthrow test status" />
</a>
<a href="https://opensource.org/licenses/MIT" rel="nofollow">
<img src="https://img.shields.io/github/license/traverse1984/betterthrow" alt="License">
</a>
<a href="https://github.com/traverse1984/betterthrow" rel="nofollow">
<img src="https://img.shields.io/github/stars/traverse1984/betterthrow" alt="GitHub stars"></a>
</p>
# Betterthrow
Define the errors your program can generate, create beautiful unions. Work in progress.
## Setup
Install the library:
```
npm install betterthrow --save
```
Recommended tsconfig.json settings:
```
{
"strict": true,
"exactOptionalPropertyTypes": true,
...
}
```
## Example
```ts
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;
};
```