JavaScript Error Hierarchy
JavaScript provides a built-in Error object and several specialized error types.
All built-in error types inherit from Error.
Error Hierarchy
Object
└─ Error
├─ AggregateError
├─ EvalError
├─ RangeError
├─ ReferenceError
├─ SyntaxError
├─ TypeError
└─ URIError
Each error type is an object created by its corresponding constructor.
The Error Object
The Error object is the base object for all built-in JavaScript errors.
Error objects typically contain a name and a message.
Example
const err = new Error("Something went wrong");
document.getElementById("demo").innerHTML =
err.name + ": " + err.message;
The result is:
Error: Something went wrong
AggregateError
An AggregateError represents multiple errors.
It is commonly used by Promise.any().
Example
new AggregateError([], "Multiple errors");
EvalError
An EvalError indicates an error related to the global eval() function.
This error type is retained mainly for compatibility reasons.
RangeError
A RangeError occurs when a value is outside the allowed range.
Example
new Array(-1);
ReferenceError
A ReferenceError occurs when JavaScript refers to a variable that does not exist.
Example
document.getElementById("demo").innerHTML = x;
SyntaxError
A SyntaxError occurs when JavaScript encounters invalid syntax.
Example
if (true {
alert("Hello");
}
TypeError
A TypeError occurs when a value is not of the expected type.
Example
const x = null;
x.toString();
URIError
A URIError occurs when an invalid URI is passed to URI encoding or decoding functions.
Example
decodeURI("%");
Inheritance
All built-in error types inherit from Error.
Example
const err = new TypeError("Wrong type");
document.getElementById("demo").innerHTML =
(err instanceof Error);
The result is:
true
Custom Error Types
You can create your own error types by extending Error.
Example
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
Summary
| Error Type | Description |
|---|---|
| Error | Generic error |
| AggregateError | Multiple errors |
| EvalError | eval() related error |
| RangeError | Value outside allowed range |
| ReferenceError | Invalid variable reference |
| SyntaxError | Invalid syntax |
| TypeError | Invalid value type |
| URIError | Invalid URI operation |