JavaScript · Middle · Question 46 of 75

What's the right way to create a custom error class?

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

Explanation

Extending Error gives you a stack trace, correct instanceof behavior and console output. You can throw anything, but a plain object has no stack. For chaining causes there's new Error('msg', { cause: err }).

Further reading

Problem with a question

JavaScript · Middle · question 46

Test yourself

Take the JavaScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz