@contract-kit/errors
v0.0.1
Published
Error catalog and error handling utilities for contract-kit
Downloads
77
Maintainers
Readme
@contract-kit/errors
Error catalog and error handling utilities for contract-kit.
Installation
npm install @contract-kit/errors
# or
bun add @contract-kit/errorsFeatures
- Error Catalog: Define your application's errors in a central location with HTTP status codes
- AppError Class: A throwable error class that domain and application code can use
- Error Factory: Type-safe factory for creating errors from your catalog
- Next.js Integration:
AppErrorinstances are automatically handled by@contract-kit/next
Usage
Define Your Error Catalog
// app/errors.ts
import { defineErrors, createErrorFactory } from "@contract-kit/errors";
export const errors = defineErrors({
CircleNotFound: {
code: "CIRCLE_NOT_FOUND",
status: 404,
message: "Circle not found",
},
Unauthorized: {
code: "UNAUTHORIZED",
status: 401,
message: "You must be signed in",
},
BadRequest: {
code: "BAD_REQUEST",
status: 400,
message: "Invalid request",
},
});
export const err = createErrorFactory(errors);Throw Errors in Your Domain/Application Code
// application/circles/getCircle.ts
import { err } from "@/app/errors";
export async function getCircle(id: string) {
const circle = await db.circles.findById(id);
if (!circle) {
throw err.appError("CircleNotFound", { details: { id } });
}
return circle;
}Next.js Integration
AppError instances thrown from your handlers are automatically handled by the @contract-kit/next adapter. They are converted to standard JSON responses with the appropriate HTTP status code.
// lib/server/router.ts
import { createNextRouter } from "@contract-kit/next";
import type { AppCtx } from "@/app/context";
export const router = createNextRouter<AppCtx>({
createContext: buildCtx,
// Optional: handle truly unexpected errors
onUnhandledError: (err, { req, ctx }) => {
console.error("Unexpected error:", err);
// Return undefined to use the default 500 response
return undefined;
},
});Error Response Format
When an AppError is thrown, it will be converted to a standard JSON response:
{
"code": "CIRCLE_NOT_FOUND",
"message": "Circle not found",
"details": { "id": "abc123" }
}The HTTP status code is taken from the error definition in the catalog.
API Reference
defineErrors<T>(defs: T): T
Type-preserving helper to define an error catalog.
createErrorFactory<T>(catalog: T): ErrorFactory<T>
Create an error factory bound to a specific catalog.
AppError
Error class that can be thrown from domain/application code.
isAppError(err: unknown): boolean
Type guard to check if an error is an AppError.
toErrorResponseBody(err: AppError): ErrorResponseBody
Convert an AppError to a standard error response body with { code, message, details }.
createErrorResponseSchema(schemaBuilder: () => TSchema): TSchema
Helper for creating error response schemas using your preferred schema library (Zod, Valibot, etc.).
License
MIT
