Course contentsShow
← JavaScript
Lesson 1153 of 2,72326. Error HandlingFree lesson

Setting the Error Name Property

How to set the name property correctly in custom errors for meaningful error identification.

Setting the Error Name Property

You'll learn: How to properly set the name property on custom error classes so they display meaningful type information when logged or inspected.

When you extend the Error class to create custom errors, JavaScript automatically gives your error instance a name property that defaults to "Error". This isn't helpful when debugging—you want to see your custom error type name instead.

Why the Name Property Matters

When an error is logged to the console or converted to a string, JavaScript uses the name property to identify what kind of error occurred. If all your custom errors say "Error", you lose the benefit of having different error types.

Think of it like labeling boxes in a warehouse. A box marked "Box" doesn't tell you anything, but one marked "FragileElectronics" immediately communicates what's inside.

Setting the Name Correctly

Inside your custom error class constructor, set this.name to match your class name:

class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = 'ValidationError';
  }
}

const error = new ValidationError('Invalid input');
console.log(error.name);     // "ValidationError"
console.log(error.toString()); // "ValidationError: Invalid input"

Without setting this.name, the error would display as "Error: Invalid input", making it harder to identify the specific error type at a glance.

Why This Matters

Setting the name properly helps with:

  • Debugging: Error logs clearly show which custom error type was thrown
  • Error identification: The toString() output is more descriptive
  • Stack traces: Console output displays your custom error name, not just "Error"

Key Takeaway: Always set this.name = 'YourClassName' in custom error constructors to ensure your errors are properly identified in logs and stack traces.