errorSubclassProperties
Reports incorrect Error subclass definitions that don't follow best practices.
✅ This rule is included in the ts logicalStrict presets.
When creating custom error classes that extend Error, there are several conventions that should be followed to ensure the errors work correctly and are easy to debug.
This rule reports:
- Invalid class names: should be capitalized and end with
Error - Missing
nameproperty: required for proper error identification - Using
this.constructor.name: won’t work after minification - Mismatched
namevalues: should match the class name - Redundant
this.messageassignments: already set bysuper()
Examples
Section titled “Examples”Correct Error Subclass
Section titled “Correct Error Subclass”class foo extends Error { constructor(message: string) { super(message); this.name = "foo"; }}class FooError extends Error { constructor(message: string) { super(message); this.name = "FooError"; }}Missing Name Property
Section titled “Missing Name Property”class CustomError extends Error { constructor(message: string) { super(message); }}class CustomError extends Error { constructor(message: string) { super(message); this.name = "CustomError"; }}Avoid this.constructor.name
Section titled “Avoid this.constructor.name”class CustomError extends Error { constructor(message: string) { super(message); this.name = this.constructor.name; }}class CustomError extends Error { constructor(message: string) { super(message); this.name = "CustomError"; }}Redundant Message Assignment
Section titled “Redundant Message Assignment”class CustomError extends Error { constructor(message: string) { super(message); this.message = message; this.name = "CustomError"; }}class CustomError extends Error { constructor(message: string) { super(message); this.name = "CustomError"; }}Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you have a specific naming convention for errors that doesn’t follow the standard pattern, or if you’re working with legacy code that can’t be easily refactored, you may need to disable this rule.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
unicorn/custom-error-definition
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.