Skip to main content

ERROR HANDLING

error-handling.ts

Canonical error strategy — single source of truth.

Stark avatarStark

WHAT THIS PATTERN TEACHES

How to define typed errors, map them to HTTP responses, and never leak internal details.

WHEN TO USE THIS

The foundation — import this in every service and API route. One error type to rule them all.

AT A GLANCE

export class ApiError extends Error {
  constructor(
    public code: ErrorCode,
    message: string,
    public status: number = 500
  ) { super(message) }
}

FRAMEWORK IMPLEMENTATIONS

TypeScript
export type ErrorCode =
  | "UNAUTHORIZED"
  | "FORBIDDEN"
  | "NOT_FOUND"
  | "VALIDATION_ERROR"
  | "LIMIT_EXCEEDED"
  | "CONFLICT"
  | "INTERNAL";

const STATUS_MAP: Record<ErrorCode, number> = {
  UNAUTHORIZED: 401,
  FORBIDDEN: 403,
  NOT_FOUND: 404,
  VALIDATION_ERROR: 400,
  LIMIT_EXCEEDED: 422,
  CONFLICT: 409,
  INTERNAL: 500,
};

export class ApiError extends Error {
← All Patterns