javascript - error instanceof X 没有按预期工作
我有一个名为 UserInputError 的类,它继承自 Error
export default class UserInputError extends Error {
constructor(message: string) {
super(message);
this.name = "UserInputError";
}
}
当我试图捕捉这个特定错误时,我使用
try {
// some code
} catch(e: any) {
// catch logic here
console.log(e instanceof UserInputError, e.name === "UserInputError");
输出是
false true
为什么 instanceof 没有按预期工作?上下文有关系吗?还是因为我使用了 any?
编辑:
这是抛出错误的代码片段
if (invalidNumberOfMethods) {
throw new UserInputError("you must chose one method");
}
注意1: 我不会使用 throw UserInputError,而是使用 throw new UserInputError
> grep -R --include "*.ts" --exclude-dir=node_modules "throw UserInputError" .
> echo $?
> 1
注意2:我在 NodeJs 中使用这个,而不是在浏览器中。