← Back to JavaScript Course | Chapter 8: Error Handling | Lesson 3 of 6

JS Custom Errors

Creating Custom Errors

You create a custom error type by extending the built-in Error class, which gives your new error inherited behavior like a message property and a proper stack trace, while letting you add your own fields on top.

Example: Creating Custom Errors

javascript
class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}
try {
  throw new ValidationError("Invalid email");
} catch (e) {
  console.log(e.name, e.message);
}

Adding Extra Information

A custom error class can accept extra constructor arguments and store them as additional properties, letting catch blocks access structured details beyond a plain message string.

Example: Adding Extra Information

javascript
class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}
try {
  throw new ValidationError("Required field", "email");
} catch (e) {
  console.log(e.field, e.message);
}

Catching Custom Errors

Because a custom error still extends Error, existing try/catch code keeps working; you can also check error instanceof YourErrorClass to handle that specific error type differently.

Example: Catching Custom Errors

javascript
class ValidationError extends Error {}
try {
  throw new ValidationError("Bad input");
} catch (e) {
  console.log(e instanceof ValidationError);
  console.log(e instanceof Error);
}

Custom Error Use Cases

Custom errors are useful when different failure categories need different handling — for example, a ValidationError versus a NetworkError might trigger completely different UI responses.

Example: Custom Error Use Cases

javascript
class ValidationError extends Error {}
class NetworkError extends Error {}
function handle(err) {
  if (err instanceof ValidationError) console.log("Show form message");
  else if (err instanceof NetworkError) console.log("Retry request");
}
handle(new NetworkError("timeout"));

Custom Error Best Practices

Name custom error classes clearly (ending in Error by convention) and keep their extra properties minimal and well-documented so other developers know what to expect when catching them.

Example: Custom Error Best Practices

javascript
class OutOfStockError extends Error {
  constructor(item) {
    super(`${item} is out of stock`);
    this.name = "OutOfStockError";
    this.item = item;
  }
}
try {
  throw new OutOfStockError("Widget");
} catch (e) {
  console.log(e.name, e.item);
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.