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;
}
}- ✓Correct answer: Extend
Error, callsuper(message)and setname - 2Create a plain
{ message }object -throwaccepts any object - 3Extend
Stringso the message is displayed correctly
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 }).