Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. TypeScript Mastery

Lesson 26 of 56 · Typescript

Custom Error Types

Duration: 15 minutes

Extending Error

class ValidationError extends Error {
  constructor(public field: string, message: string) {
    super(message);
    this.name = "ValidationError";
  }
}

function assertPositive(n: number) {
  if (n < 0) throw new ValidationError("n", "must be positive");
}

Type Guard for custom errors

function isValidationError(e: unknown): e is ValidationError {
  return e instanceof ValidationError;
}

try {
  assertPositive(-5);
} catch (e) {
  if (isValidationError(e)) console.error(e.field, e.message);
}

Info

Preserve stack traces by extending Error directly and calling super(message).

Previous: Promises & GenericsNext: TypeScript with React – JSX Typing