tagged-error-kit
v0.1.1
Published
Result-agnostic tagged Error classes with exhaustive matching and bounded diagnostics
Readme
tagged-error-kit
Tagged Error classes and exhaustive matching for TypeScript.
tagged-error-kit provides a class factory for defining native errors with literal tags and typed properties. It also provides guards, exhaustive and partial matching, and bounded diagnostic output.
Install
npm install tagged-error-kitRequires TypeScript 5.4.5 or newer and an ES2022 runtime.
Quick start
Define errors by extending the class returned by TaggedError:
import { TaggedError } from "tagged-error-kit";
class OrderNotFoundError extends TaggedError("OrderNotFoundError")<{
orderId: string;
message: string;
}> {}
class PaymentDeclinedError extends TaggedError("PaymentDeclinedError")<{
reason: "insufficient-funds" | "card-expired";
message: string;
}> {}
type CheckoutError = OrderNotFoundError | PaymentDeclinedError;Generated instances extend Error. Their _tag is a string literal type, and constructor properties are readonly in the TypeScript type:
const error = new PaymentDeclinedError({
reason: "insufficient-funds",
message: "Payment was declined",
});
error instanceof Error; // true
error instanceof PaymentDeclinedError; // true
error._tag; // "PaymentDeclinedError"
error.reason; // "insufficient-funds" | "card-expired"Call .match() on an error union with one handler for each tag:
declare const checkoutError: CheckoutError;
const response = checkoutError.match({
OrderNotFoundError: (error) =>
Response.json({ message: "Order not found", orderId: error.orderId }, { status: 404 }),
PaymentDeclinedError: (error) =>
Response.json({ message: "Payment was declined", reason: error.reason }, { status: 402 }),
});Each handler receives the error type corresponding to its tag. Exhaustiveness is based on the static type of the matched value. If another variant is added to CheckoutError, the handler object must include that tag.
Narrow unknown errors
Every generated class has a static .is() guard. It checks whether a value is an instance of the concrete class:
declare const value: unknown;
if (PaymentDeclinedError.is(value)) {
value.reason; // "insufficient-funds" | "card-expired"
}Use isTaggedError() or the equivalent TaggedError.is() to check the general tagged-error contract:
import { isTaggedError } from "tagged-error-kit";
if (isTaggedError(value)) {
console.error(value.prettyPrint());
}isTaggedError() requires the value to be an Error with a string _tag and callable match, prettyPrint, and toJSON properties.
Standalone matching
matchError() is the standalone form of .match(). It accepts generated tagged errors and other Error values with a string _tag. Literal tag types determine the handler keys:
import { matchError } from "tagged-error-kit";
const message = matchError(checkoutError, {
OrderNotFoundError: (error) => `Order ${error.orderId} was not found`,
PaymentDeclinedError: (error) => `Payment failed: ${error.reason}`,
});The return type is the union of the handler return types. Explicit type parameters can constrain every handler to one return type.
Partial matching
matchErrorPartial() handles selected variants and returns unhandled errors unchanged:
import { matchErrorPartial } from "tagged-error-kit";
const result = matchErrorPartial(checkoutError, {
OrderNotFoundError: (error) => `Missing order: ${error.orderId}`,
});
// string | PaymentDeclinedErrorAn optional fallback handles the remaining variants. Its argument is narrowed to the unhandled error types:
const message = matchErrorPartial(
checkoutError,
{
OrderNotFoundError: (error) => `Missing order: ${error.orderId}`,
},
(error) => `Payment failed: ${error.reason}`,
);Diagnostics and logging
In Node.js, tagged errors implement the custom inspection hook used by console and node:util.inspect. The output contains the message, enumerable context properties, stack, and cause chain. prettyPrint() returns the same format:
console.error(error);
// [PaymentDeclinedError] Payment was declined
// reason: "insufficient-funds"
// ...native stackJSON.stringify(new Error("message")) normally produces {} because native error fields are non-enumerable. Tagged errors implement toJSON(), which returns a depth- and size-bounded, cycle-safe diagnostic object:
error.toJSON();
// {
// _tag: "PaymentDeclinedError",
// name: "PaymentDeclinedError",
// message: "Payment was declined",
// reason: "insufficient-funds",
// stack: "PaymentDeclinedError: Payment was declined\n..."
// }Diagnostic output includes enumerable context and can therefore contain sensitive values. Redact those values before logging. toJSON() does not provide a transport format or deserialization contract.
API
| Export | Purpose |
| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| TaggedError(tag) | Create a tagged Error class with static .is() and instance .match(), prettyPrint(), and toJSON() |
| isTaggedError(value) | Check the complete structural tagged-error contract |
| matchError(error, handlers) | Exhaustively match a tagged error union |
| matchErrorPartial(error, handlers, fallback?) | Transform selected variants and preserve or handle the rest |
Exported types: AnyTaggedError, TaggedErrorClass, and TaggedErrorInstance.
Runtime support
tagged-error-kit is ESM-only, targets ES2022, and has zero runtime dependencies. Its declared Node.js minimum is version 18. The custom console inspection behavior is Node-specific; prettyPrint() and toJSON() do not depend on that hook.
