unicorn/no-useless-error-capture-stack-trace
Disallow Error.captureStackTrace() in the constructor of an Error subclass
has suggestions
The Error constructor already records the stack when super() runs. Calling Error.captureStackTrace(this, MyError) in the subclass's constructor does that work a second time.
The rule checks classes that extend a built-in error such as Error, TypeError or RangeError. It reports the call when the second argument is the class itself, written as its name, new.target or this.constructor.
--fix-suggestions removes the call.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/no-useless-error-capture-stack-trace" = "error" # or "warn"Examples#
example.js1 problem
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
Error.captureStackTrace(this, ValidationError)Do not use Error.captureStackTrace(…) in the constructor of an Error subclass;
}
}example.jsNo problems
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}Hiding another function from the stack is a real use, and so is calling it in a class that doesn't extend a built-in error:
example.jsNo problems
class ParseError extends SyntaxError {
constructor(message) {
super(message);
Error.captureStackTrace(this, parse);
}
}
class Failure {
constructor() {
Error.captureStackTrace(this, Failure);
}
}