Types of errors in JavaScript
In JavaScript every error inherits from the base Error class, and there are seven built in specialised types: ReferenceError, TypeError, RangeError, SyntaxError, URIError, EvalError and AggregateError. Each of them signals its own class of problem, and on top of that you can always create your own error type by extending Error.
Theory
TL;DR
Erroris the base class with thename,messageandstackproperties.ReferenceError,TypeErrorandRangeErrorare the three most common runtime errors.SyntaxErrorhappens at parse time, so an ordinarytry...catchcannot catch it.URIErrorconcerns the URI encoding functions,EvalErroris practically unused.AggregateErrorbundles several errors at once, for example inPromise.any().- You create your own error type with
class MyError extends Error.
Quick example
try {
null.toString();
} catch (e) {
console.log(e.name); // TypeError
console.log(e.message); // Cannot read properties of null
}Error, the base error class
This is the universal type that all other errors inherit from. If you do not know which error type fits, you can simply use Error.
throw new Error("Something went wrong");Properties of an error object:
name, the name of the error ("Error")message, the descriptionstack, the stack trace, showing where exactly the error happened
Runtime errors: ReferenceError, TypeError, RangeError
ReferenceError, a reference error. It occurs when the code touches a variable that does not exist, or a binding that is not available in the current scope.
console.log(x); // ReferenceError: x is not definedIt can also arise from incorrect use of this.
TypeError, a type error. It happens when an operation is applied to a value of an unsuitable type, or when you try to call something that is not a function.
let n = null;
console.log(n.toString()); // TypeError: Cannot read properties of nulllet func = 123;
func(); // TypeError: func is not a functionRangeError, going outside the allowed limits. It occurs when the value passed in is outside the acceptable range.
new Array(-5); // RangeError: Invalid array length(123.456).toFixed(200);
// RangeError: toFixed() digits argument must be between 0 and 100SyntaxError, URIError, EvalError and AggregateError
SyntaxError, a syntax error. An error caused by breaking JavaScript syntax. The engine cannot parse the code, so the program does not even start.
eval("if (true { console.log('hi'); }");
// SyntaxError: Unexpected token '{'Such errors cannot be caught with
try...catch, because they happen before execution begins. The exception is code that is parsed separately and later, as in theevalexample above or insidenew Function(...).
URIError, an error in the URI functions. It happens when encodeURI(), decodeURI(), encodeURIComponent() or decodeURIComponent() receive malformed data.
decodeURIComponent("%");
// URIError: URI malformedEvalError, an error while using eval(). Rare in modern implementations. It was originally used when eval() was applied incorrectly.
throw new EvalError("Incorrect use of eval()");AggregateError, a set of errors. It arises when a single operation returns several errors at once, for example with Promise.any().
Promise.any([
Promise.reject(new Error("Error 1")),
Promise.reject(new Error("Error 2")),
]).catch(e => console.log(e.errors));Output:
[Error: Error 1, Error: Error 2]Custom errors
You can create your own error classes by extending Error:
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
throw new ValidationError("Invalid email");Output:
ValidationError: Invalid emailThis approach lets you tell domain errors from technical ones right inside catch, with if (e instanceof ValidationError).
Summary table
| Error type | When it occurs | Example |
|---|---|---|
| Error | Base class for all errors | throw new Error("Failure") |
| ReferenceError | The variable is not defined | console.log(x) |
| TypeError | Wrong value type | null.toString() |
| RangeError | Value outside the allowed range | new Array(-1) |
| SyntaxError | A syntax error | eval("if (true {") |
| URIError | An error encoding or decoding a URI | decodeURI("%") |
| EvalError | An eval() error (almost never used) | throw new EvalError() |
| AggregateError | Several errors at once | Promise.any([...]) |
Common mistakes
- Expecting
try...catchto catch aSyntaxErrorin your own file. That code will not run at all, because parsing happens before execution. - Catching everything with one
catch (e)and never looking ate.name. Without a type check you handle a validation failure exactly like a network outage. - Forgetting
super(message)in a custom error class. Thenmessagecomes out empty and the stack is incomplete. - Confusing
ReferenceErrorandTypeError. The variable does not exist at all, that is aReferenceError; the variable exists but its value isnullorundefined, that is already aTypeError. - Relying on
EvalError. Modern engines hardly ever throw it, so do not build logic around it.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.