Know which error you caught
JavaScript has a small set of built-in Error subtypes, each thrown by specific
operations. Recognising the subtype tells you the class of bug instantly. This
reference lists every standard error type, what throws it, a typical message and
how to catch it with instanceof.
How it works
Every built-in error inherits from Error and carries name, message and a
stack. The engine throws the most specific subtype for the failure, which you
can branch on:
try {
null.foo; // TypeError: Cannot read properties of null
} catch (e) {
if (e instanceof TypeError) handleType(e);
else if (e instanceof RangeError) handleRange(e);
else throw e; // re-throw anything you do not handle
}
Because all subtypes extend Error, e instanceof Error is always true — order
your checks from most specific to least, and re-throw what you cannot handle.
Tips and notes
instanceofcan fail across realms (iframes, worker boundaries) where each has its ownErrorconstructor — checke.nameas a fallback in that case.SyntaxErrorfrom static source is uncatchable; only runtime-parsed code (JSON.parse,eval,new Function) throws a catchable one.- Use
Error.cause(new Error(msg, { cause })) to chain a lower-level error. - Custom errors should
extend Error, callsuper(message)and setthis.name. - A “Maximum call stack size exceeded” message is a
RangeError, usually from unbounded recursion.