unicorn/custom-error-definition
Enforce that subclasses of Error set name and pass the message to super()
A class that extends Error inherits name, so without more work String(new ValidationError("Bad email")) is "Error: Bad email", and a check such as error.name === "ValidationError" never matches.
The rule looks at every named class that extends Error or a class with a name like TypeError or HttpError. It reports:
- a
namethat's missing, or is anything other than the class name written as a string - a constructor that doesn't call
super() this.message = messageinstead ofsuper(message)- a class name that doesn't end in
Erroror doesn't start with a capital letter exports.A = class B extends Error, where the two names differ
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/custom-error-definition" = "error" # or "warn"Examples#
example.js1 problem
class ValidationError extends Error {}The name property should be set to ValidationError.example.js2 problems
class ValidationError extends Error {
constructor(message) {
super();Pass the error message to super() instead of setting this.message.
this.message = message;
this.name = this.constructor.nameThe name property should be set to ValidationError.;
}
}example.js1 problem
class ValidationInvalid class name, use ValidationError. extends Error {
name = "Validation";
}example.jsNo problems
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}A class field works too:
example.jsNo problems
class ValidationError extends Error {
name = "ValidationError";
}