Check if a value is an Error in JavaScript
Intermediate · 3 min read
In JavaScript you can throw anything: an Error, a string, a number, even null. So when a catch block or an error logger receives something, it can't assume it has a proper error with a message and a stack trace. It has to check first.
In this tutorial you will write isError, a check that recognizes every kind of error, including your own custom ones. Then you will find the one place where the usual check gives the wrong answer. You should know what an object is and have seen try and catch.
What an Error is
An error is an object made with new Error(...). It carries a name, a message, and a stack (the list of function calls that led to it). JavaScript also has more specific kinds, like TypeError and RangeError, and each one is built on top of Error:
const e = new TypeError('bad input');
console.log(e.name); // TypeError
console.log(e.message); // bad input
console.log(typeof e); // object
typeof only says 'object', which doesn't help: arrays and dates say that too. We need a check that asks about the family the value belongs to.
instanceof: "were you made by this?"
value instanceof Error asks whether value was made by Error, or by anything built on top of it. Think of it as checking a family tree. A TypeError is a child of Error, so it passes both checks:
const e = new TypeError('bad input');
console.log(e instanceof TypeError); // true
console.log(e instanceof Error); // true
console.log(e instanceof RangeError); // false
Here is the exercise. Have a go on your own if you like, or read on and we will build it step by step.
2 Is the value an error?
fairDetect an Error, including the subclasses like TypeError and your own custom ones. Then find where instanceof gives the wrong answer.
Stuck? Three hints, smallest first
- 1.
instanceof Errorcovers every subclass, because they all inherit from it. - 2. It compares against one particular
Errorconstructor. A value from an iframe or worker has a different one. - 3. The tag check is
‘Error’for every built-in error type, includingTypeError.
Step 1: the instanceof check
const isError = (v) => v instanceof Error;
console.log(isError(new Error('boom'))); // true
console.log(isError(new TypeError('boom'))); // true
console.log(isError(new RangeError('boom'))); // true
console.log(isError('boom')); // false
console.log(isError(null)); // false
A string isn't an error, even if it was thrown like one. null instanceof Error is simply false; it doesn't crash.
Step 2: your own error class
Apps often make their own kinds of error, so a handler can tell "no seats left" apart from "network down". You do that with a class that extends Error:
class TicketError extends Error {
constructor(message) {
super(message);
this.name = 'TicketError';
}
}
const isError = (v) => v instanceof Error;
const e = new TicketError('no seats');
console.log(isError(e)); // true
console.log(e instanceof TicketError); // true
console.log(e.name); // TicketError
console.log(e.message); // no seats
extends Error puts TicketError in the Error family. super(message) runs the Error part of the setup, which stores the message. Setting this.name makes logs show TicketError instead of plain Error.
Step 3: a lookalike is not an error
What about an ordinary object with the same properties?
const isError = (v) => v instanceof Error;
const fake = { name: 'Error', message: 'not really an error', stack: 'made up' };
console.log(isError(fake)); // false
That is the right answer. instanceof checks where the value came from, not what it looks like.
Step 4: where instanceof gets it wrong
Each browser window, iframe and web worker has its own copy of the built-ins, including its own Error. Each copy is called a realm. An error made in an iframe was built by that iframe's Error, so instanceof Error in the main page says false, even though it plainly is an error.
You can see the same thing in Node.js, which can create a fresh realm with its vm module:
const vm = require('node:vm');
const foreignError = vm.runInNewContext("new Error('from another realm')");
console.log(foreignError instanceof Error); // false
console.log(Object.prototype.toString.call(foreignError)); // [object Error]
The second line is the tag check: a built-in description of the value that doesn't depend on which realm made it. Wrap it in a small helper:
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
const isErrorLike = (v) => tag(v) === 'Error';
const fake = { name: 'Error', message: 'not really an error' };
console.log(isErrorLike(new Error('x'))); // true
console.log(isErrorLike(new TypeError('x'))); // true
console.log(isErrorLike(fake)); // false
.slice(8, -1) cuts 'Error' out of '[object Error]'. The lookalike still fails, because its tag is 'Object'.
Step 5: telling the kinds apart
The tag check has a cost. Every built-in error kind gets the same tag:
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
console.log(tag(new TypeError('x'))); // Error
console.log(tag(new RangeError('x'))); // Error
console.log(new TypeError('x').name); // TypeError
So use the tag to answer "is it an error at all?", and read .name when you need to know which kind.
The full solution
The panel has both checks, the TicketError class and the lookalike object. Press Run to see the tags, the names and all the checks.
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
const isError = (v) => v instanceof Error;
// Survives crossing between windows, workers or iframes, where the value was
// built by a *different* Error constructor and instanceof therefore fails.
const isErrorLike = (v) => tag(v) === 'Error';
class TicketError extends Error {
constructor(message) {
super(message);
this.name = 'TicketError';
}
}
// A hand-made lookalike: right shape, wrong ancestry. This is the case that
// separates the two checks.
const fake = { name: 'Error', message: 'not really an error', stack: 'made up' };
// Simulating the cross-realm problem without a second window: an object whose
// prototype chain does not include this realm's Error.
const foreign = Object.create(null);
foreign.name = 'Error';
foreign.message = 'from another realm';
console.log('tag(new Error) :', tag(new Error('x')));
console.log('tag(new TypeError) :', tag(new TypeError('x')), '<- also "Error"');
console.log('tag(new TicketError):', tag(new TicketError('x')));
console.log('name of a subclass :', new TypeError('x').name);
console.log('the lookalike passes instanceof?', isError(fake));
console.log('the lookalike passes the tag check?', isErrorLike(fake));
Output
13 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 13 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a plain Error', isError(new Error('boom')), true);
test('a TypeError, because it inherits', isError(new TypeError('boom')), true);
test('a RangeError too', isError(new RangeError('boom')), true);
test('a custom subclass', isError(new TicketError('no seats')), true);
test('a string is not an error', isError('boom'), false);
test('null is not', isError(null), false);
test('an object shaped like one is not', isError(fake), false);
test('the tag is "Error" for every built-in type', ['Error', 'TypeError', 'RangeError'].map((n) => tag(new globalThis[n]('x'))), ['Error', 'Error', 'Error']);
test('so the tag cannot tell you which kind it is', tag(new TypeError('x')) === tag(new RangeError('x')), true);
test('the name property can', new TypeError('x').name, 'TypeError');
test('and a subclass sets its own', new TicketError('x').name, 'TicketError');
test('the tag check also rejects the lookalike', isErrorLike(fake), false);
test('a subclass is still an instance of its own class', new TicketError('x') instanceof TicketError, true);
instanceof Error is what to reach for, and it has one real failure: it checks against the Error constructor of the current window. An error thrown inside an iframe or a web worker was built by a different constructor, so instanceof says no even though it plainly is an error. The tag check has the opposite tradeoff — it works across realms, but it flattens TypeError and RangeError both to 'Error', so use .name when you need the specific kind.
Common mistakes
- Checking for a
messageproperty. Any object can have one. Check the value's family withinstanceofor the tag. - Forgetting
super(message)in a custom class. JavaScript refuses to let you usethisbeforesuperruns, so the constructor throws. - Using the tag to find the kind of error.
TypeErrorandRangeErrorboth give'Error'. Read.nameinstead.
Try it yourself
- Write
toError(v)that returnsvif it is an error and otherwise wraps it:new Error(String(v)). - Make a
NetworkErrorclass with an extrastatusproperty, and check thatisErroraccepts it. - In a
catchblock, useisErrorto logerr.messagefor real errors and the raw value for anything else.