Skip to content
jshacks.dev
Fundamentals

Detect a real error with Error.isError

Detect a real error object with Error.isError, which works across contexts and for DOMException where instanceof Error gives the wrong answer. Node.js 24.

2 min read
Summarize in AI

error instanceof Error is false for an error from another iframe or a vm context, because each of those has its own global Error. Node.js 24 added Error.isError(), which checks for a real error object instead.

JavaScript
import { runInNewContext } from 'node:vm';

const real = new TypeError('boom');
const fake = { name: 'Error', message: 'boom', stack: '' };

console.log(Error.isError(real), real instanceof Error);
console.log(Error.isError(fake), fake instanceof Error);
console.log(Error.isError(new DOMException('x', 'AbortError')));
console.log(Error.isError('Error: text'));

const foreign = runInNewContext('new Error("from another context")');
console.log(foreign instanceof Error, Error.isError(foreign));
Text
true true
false false
true
false
false true

The first line shows the ordinary case, where both checks agree on a TypeError. The fake object is the reason to prefer the new method: it has a name, a message and a stack, but it is not an error, and Error.isError() returns false for it. new DOMException() counts as an error. The last line is the cross-context problem: an error built inside vm.runInNewContext fails instanceof Error, because it inherits from a different Error constructor, while Error.isError() still returns true. The check looks at an internal slot that only real errors have, as the specification for Error.isError says.

It does not tell you what kind of error it is, so keep using error.name or instanceof for a known class in the same context. Node.js 22 and older do not have it. For a promise rejection that may be a string, run the check before you read .message.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.