← 中文资源

简体中文版本

Error.isError 校验未知值

Error.isError 检查内部槽位而不是原型链:伪装的 message 对象会被识破,structuredClone 出来的错误依然通过,未知捕获值一次分类到位。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

real: TypeError
not an error: string
not an error: object
not an error: object
rejection value is Error: false
rejection value: plain string
caught is Error: true | TypeError
clone is Error: true

实现说明

循环只出现在 for (const candidate of candidates),它的每次迭代处理一个元素。await 标出每个异步边界——没有 fire-and-forget。 顶层就这几处状态:candidates、rejection、caught。

使用要点

  • 跑完文件,输出里会留下标记——rejection value is Error:、rejection value:、caught is Error:。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 文件的状态由几个模块级绑定持有:candidates、rejection、caught。

核心语句

const caught = await rejection.catch((value) => value);
const rejection = Promise.reject('plain string');

代码示例

// Error.isError is the reliable test for unknown values that may be Errors:
// it checks the internal slot, so fakes fail and cloned errors pass.
const candidates = [new TypeError('bad input'), 'boom', { message: 'fake' }, null];

for (const candidate of candidates) {
  const isError = Error.isError(candidate);
  console.log(isError ? `real: ${candidate.name}` : `not an error: ${typeof candidate}`);
}

// A rejected non-Error value stays non-Error through the catch path
const rejection = Promise.reject('plain string');
const caught = await rejection.catch((value) => value);
console.log('rejection value is Error:', Error.isError(caught));
console.log('rejection value:', caught);

// Caught runtime errors are real Errors
try {
  null.foo();
} catch (thrown) {
  console.log('caught is Error:', Error.isError(thrown), '|', thrown.name);
}

// Structured cloning preserves the Error slot as well
console.log('clone is Error:', Error.isError(structuredClone(new RangeError('range'))));