Error.isError Validates Unknown Values

Error.isError tests the internal slot, so fake message objects fail, cloned errors pass, and unknown catch values get one honest classification.

JavascriptResilience

Code

javascriptsnippet
24 lines
// 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'))));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How it works

Repetition is confined to for (const candidate of candidates) — the rest of the file is straight-line. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Demo state sits in top-level bindings: candidates, rejection, caught.

Points of care

  • The import surface (if any) is all standard library, all versioned with the language itself.

Using it

Expect labeled output — rejection value is Error:, rejection value:, caught is Error: — when the file runs.

The key statements, annotated

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

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `candidates`, `rejection`, `caught`.