Skip to main content

Lesson 3 of 7

Error Hierarchy - Typed Application Errors

Production applications need a typed error hierarchy - not just `new Error()` everywhere. A structured error class with HTTP status, error code, and optional context enables consistent API error responses, better logging, and client-side error handling branching.

11 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Typed Error Hierarchy & Structured Error Handling

Typed Error Hierarchy & Structured Error Handling
// ── Base application error ────────────────────────────────────
abstract class AppError extends Error {
  abstract readonly statusCode: number;
  abstract readonly code:       string;

  constructor(
    message: string,
    public readonly context?: Record<string, unknown>,
  ) {
    super(message);
    this.name = this.constructor.name;
    // Maintains proper prototype chain for instanceof checks:
    Object.setPrototypeOf(this, new.target.prototype);
  }

  toJSON(): object {
    return {
      error:   this.code,
      message: this.message,
      ...(this.context && { context: this.context }),
    };
  }
}

// ── Concrete error types ──────────────────────────────────────
class NotFoundError extends AppError {
  readonly statusCode = 404;
  readonly code       = "NOT_FOUND";

  constructor(resource: string, id: number | string) {
    super(`${resource} with ID ${id} not found`, { resource, id });
  }
}

class ValidationError extends AppError {
  readonly statusCode = 400;
  readonly code       = "VALIDATION_ERROR";

  constructor(
    public readonly fields: Record<string, string[]>,
  ) {
    super("Validation failed", { fields });
  }

  override toJSON(): object {
    return { ...super.toJSON(), fields: this.fields };
  }
}

class UnauthorizedError extends AppError {
  readonly statusCode = 401;
  readonly code       = "UNAUTHORIZED";
  constructor(message = "Authentication required") { super(message); }
}

class ForbiddenError extends AppError {
  readonly statusCode = 403;
  readonly code       = "FORBIDDEN";
  constructor(action: string) { super(`Not permitted to: ${action}`, { action }); }
}

class ConflictError extends AppError {
  readonly statusCode = 409;
  readonly code       = "CONFLICT";
}

// ── Global Express error handler ──────────────────────────────
import { ZodError } from "zod";

function errorHandler(
  error:  unknown,
  req:    Request,
  res:    Response,
  _next:  NextFunction,
): void {
  const reqId = req.requestId ?? "?";

  // AppError hierarchy - structured response
  if (error instanceof AppError) {
    res.status(error.statusCode).json({ requestId: reqId, ...error.toJSON() });
    return;
  }

  // Zod validation errors
  if (error instanceof ZodError) {
    res.status(400).json({
      requestId: reqId,
      error:  "VALIDATION_ERROR",
      message: "Validation failed",
      fields: error.flatten().fieldErrors,
    });
    return;
  }

  // Unknown errors - log full details, return safe response
  console.error(`[${reqId}] Unhandled error:`, error);
  res.status(500).json({ requestId: reqId, error: "INTERNAL_ERROR", message: "Internal server error" });
}

// ── Service usage ─────────────────────────────────────────────
async function getTask(id: number): Promise<Task> {
  const task = await taskRepo.findById(id);
  if (!task) throw new NotFoundError("Task", id);      // typed, specific
  return task;
}

async function deleteTask(id: number, requesterId: number): Promise<void> {
  const task = await getTask(id);          // throws NotFoundError if missing
  if (task.assigneeId !== requesterId) {
    throw new ForbiddenError(`delete task ${id}`);  // typed access check
  }
  await taskRepo.delete(id);
}

Common Mistakes

  • Using `instanceof` without fixing prototype chain - subclasses of built-in classes (like Error) have prototype issues in TypeScript. Always call `Object.setPrototypeOf(this, new.target.prototype)` in the constructor.
  • Throwing raw strings - `throw 'Not found'` produces an `unknown` in catch that callers can't narrow with `instanceof Error`. Always throw Error instances.
  • Exposing stack traces in production - never include `error.stack` in API responses. Log it server-side with the requestId for debugging, but return only a safe message to clients.

Tip

Tip

Practice Error Hierarchy Typed Application Errors in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Error Hierarchy - Typed Application Errors

Practice Task

Note

Practice Task - (1) Write a working example of Error Hierarchy Typed Application Errors from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Error Hierarchy Typed Application Errors is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • Production applications need a typed error hierarchy - not just `new Error()` everywhere.
  • Using `instanceof` without fixing prototype chain - subclasses of built-in classes (like Error) have prototype issues in TypeScript. Always call `Object.setPrototypeOf(this, new.target.prototype)` in the constructor.
  • Throwing raw strings - `throw 'Not found'` produces an `unknown` in catch that callers can't narrow with `instanceof Error`. Always throw Error instances.
  • Exposing stack traces in production - never include `error.stack` in API responses. Log it server-side with the requestId for debugging, but return only a safe message to clients.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done