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.
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.
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));true true
false false
true
false
false trueThe 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.