首页 > 解决方案 > 捕获以某种方式影响对象评估的错误

问题描述

我有这样的代码结构:

class CustomError {
  constructor(status, error = null, message = null) {
    this.status = status;
    this.error = error;
    this.message = message;
  }
}

const foo = async function() {
  throw new CustomError('foo error');
}

const bar = async function() {
  try {
    foo();
  } catch (error) {
    if (error instanceof CustomError) {
      throw error;
    }
    throw new CustomError('bar error');
  }
}

bar();

这会引发条形错误。

我把它放在if声明之前: console.log(error instanceof CustomError, error) which 记录:

false
CustomError {status: "foo", message: null, error: null}

这似乎是矛盾的。如果它记录errorCustomError不应该error instanceof CustomError返回true

标签: javascripterror-handlingtry-catch

解决方案


推荐阅读