π·οΈ Type-safe error handling in TypeScript without the hassle of custom error classes.
- π― Type-safe: Full TypeScript support with type inference
- πͺΆ Lightweight: Zero dependencies, minimal code
- π Easy debugging: Clear error messages with structured data
- π‘ Simple API: No need to create custom error classes
Choose your preferred package manager:
npm install @nakanoaas/tagged-error # npm
pnpm add @nakanoaas/tagged-error # pnpm
yarn add @nakanoaas/tagged-error # yarn
For Deno users (ESM only):
deno add jsr:@nakanoaas/tagged-error # deno
npx jsr add @nakanoaas/tagged-error # npm
pnpm dlx jsr add @nakanoaas/tagged-error # pnpm
import { TaggedError } from "@nakanoaas/tagged-error";
// Example: A function that might fail in different ways
function divideAndSquareRoot(num: number, divisor: number) {
if (divisor === 0) {
return new TaggedError("DIVISOR_IS_ZERO", {
message: "Cannot divide by zero",
});
}
const result = num / divisor;
if (result < 0) {
return new TaggedError("NEGATIVE_RESULT", {
message: "Cannot calculate square root of negative number",
cause: { value: result },
});
}
return Math.sqrt(result);
}
// Using the function
const result = divideAndSquareRoot(10, 0);
// Type-safe error handling
if (result instanceof TaggedError) {
switch (result.tag) {
case "DIVISOR_IS_ZERO":
console.error("Division by zero error:", result.message);
break;
case "NEGATIVE_RESULT":
console.error(
"Negative result error:",
result.message,
"Value:",
result.cause.value,
);
break;
}
} else {
console.log("Result:", result); // result is typed as number
}
Traditional error handling in TypeScript often involves creating multiple error classes or using string literals. Tagged Error provides a simpler approach:
// β Traditional approach - lots of boilerplate
class DivisorZeroError extends Error {
constructor() {
super("Cannot divide by zero");
}
}
// β
Tagged Error approach - clean and type-safe
return new TaggedError("DIVISOR_IS_ZERO", {
message: "Cannot divide by zero",
});
new TaggedError(tag: string, options?: {
message?: string;
cause?: any;
})
tag
: A string literal that identifies the error typeoptions
: Optional configuration objectmessage
: Human-readable error messagecause
: Additional error context data
MIT Β© Nakano as a Service