0Pricing
TypeScript Academy · Lesson

Typed Error Classes and Hierarchies

Create custom error classes with discriminated types.

Typed Error Classes and Hierarchies is a free TypeScript Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Welcome

Custom error classes in TypeScript give errors a type hierarchy for safe, structured handling.

Extending Error

Create a base AppError class with a statusCode.
class AppError extends Error {
  constructor(public message: string, public statusCode = 500) {
    super(message);
    this.name = 'AppError';
  }
}

Error Hierarchy

Build typed subclasses for specific error types.
class NotFoundError extends AppError {
  constructor(resource: string) { super(`${resource} not found`, 404); }
}
class ValidationError extends AppError {
  constructor(public fields: string[]) { super('Validation failed', 400); }
}

Using instanceof

Use instanceof to narrow error types in catch blocks.
try { doSomething(); }
catch (err) {
  if (err instanceof NotFoundError) res.status(404).json({ error: err.message });
  else if (err instanceof ValidationError) res.status(400).json({ fields: err.fields });
}

Discriminated Error Union

Use a discriminated union for typed error handling.
type AppError =
  | { kind: 'not_found'; resource: string }
  | { kind: 'unauthorized' }
  | { kind: 'validation'; fields: string[] };

Error Factory Functions

Create factory functions for each error type.
const errors = {
  notFound: (r: string) => new NotFoundError(r),
  unauthorized: () => new AppError('Unauthorized', 401),
};

Error Serialization

Serialize errors for API responses.
function serializeError(err: AppError): Record<string, unknown> {
  return { error: err.message, code: err.statusCode, name: err.name };
}

Setting this.name

Always set this.name to the error class name for correct error identification in logs.
class MyError extends Error {
  readonly name = 'MyError' as const;
  constructor(msg: string) { super(msg); }
}

Error in Express

Use typed custom errors in Express error handlers.
app.use((err: unknown, req: Request, res: Response, next: NextFunction) => {
  if (err instanceof AppError) {
    res.status(err.statusCode).json({ error: err.message });
  } else {
    res.status(500).json({ error: 'Internal error' });
  }
});

Error Logging Pattern

Log errors with their type and message for observability.
function logError(err: unknown): void {
  if (err instanceof Error) console.error(`[${err.name}] ${err.message}`);
  else console.error('Unknown error:', err);
}

Testing Error Types

Test that functions throw the correct error types.
test('throws NotFoundError for missing user', async () => {
  await expect(getUser(999)).rejects.toThrow(NotFoundError);
});

Quick Check

What TypeScript keyword checks if an object is an instance of a class at runtime?

Recap

Typed Error Classes and Hierarchies: you learned the key concepts of this topic and how to apply them in real TypeScript projects.

Frequently asked questions

Is the “Typed Error Classes and Hierarchies” lesson free?

Yes — the full text of “Typed Error Classes and Hierarchies” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Typed Error Classes and Hierarchies”?

Create custom error classes with discriminated types. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Typed Error Classes and Hierarchies” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Typed Error Classes and Hierarchies
  2. The Result Pattern: Ok and Err
  3. Narrowing Caught Errors (unknown vs Error)
  4. Error Handling in Async TypeScript Code
← Back to TypeScript Academy