ReviseAlgo Logo

Error Handling & Patterns

Custom Error Classes

Create custom application error hierarchies with prototypes and context payloads.

Last Updated: July 29, 2026 10 min read

Custom error classes allow categorizing failures (e.g. NotFoundError, ValidationError) with specific status codes and context data.

1. Introduction & Architecture

2. Deep Dive & Core Concepts

When extending built-in Error in ES5/ES6, fixing prototype chain assignment via Object.setPrototypeOf(this, new.target.prototype) ensures instanceof checks work reliably.

3. Basic Code Example

4. Advanced Production Patterns

5. Interactive Code Playground

class UnauthorizedError extends Error {
  readonly statusCode = 401;
  constructor(msg: string = "Unauthorized") {
    super(msg);
    Object.setPrototypeOf(this, UnauthorizedError.prototype);
  }
}

const err = new UnauthorizedError(); console.log(err.name, err.statusCode, err instanceof UnauthorizedError);

6. Common Pitfalls & Edge Cases

Warning: Forgetting Object.setPrototypeOf(this, TargetClass.prototype) inside custom error constructors can cause err instanceof CustomError to return false in transpiled code!

7. Interview Q&A & Quizzes

Q: Why is Object.setPrototypeOf needed in custom Error classes?

A: ES5 prototype inheritance transpilation breaks native ES Error prototype chain binding.

8. Summary Comparison Table

Custom Error ClassPurposeStatus Code
NotFoundErrorMissing database or API resource404
ValidationErrorInvalid payload or field inputs400
| UnauthorizedError | Authentication failures | 401 |