Chapter XXIII · Error Handling

Custom Errors

Custom errors are user-defined error classes extending the built-in JavaScript `Error` object for specialized error reporting.

01 How It Works

Think of custom colored warning alert tags created specifically for specialized hazard items.

By extending `Error`, custom error types can carry specialized properties and maintain clear error classification hierarchies.

example.js
class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}
throw new ValidationError("Invalid email input");
  1. 1. Create a class extending `Error`.

  2. 2. Call `super(message)` in the constructor.

  3. 3. Throw and catch specific custom error types.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
class AuthenticationError extends Error {
  constructor(msg) {
    super(msg);
    this.status = 401;
  }
}

Key Takeaway

Custom errors allow fine-grained exception classification and specialized debugging.

Related Concepts