实现说明
循环只出现在 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'))));