Example 1 — TypeError
Wrong type of value.
try {
const x = null;
x();
} catch (err) {
console.log(err.name);
console.log(err instanceof TypeError);
} TypeError true

JavaScript ships several built-in Error subclasses. They all extend Error, so err instanceof Error is true, while err.name tells you the specific kind.
This overview keeps every common type in one place. For throw / try / catch basics, start at the Error hub.
Create and throw a specific type:
throw new TypeError("x is not a function");
throw new RangeError("Invalid array length");
throw new AggregateError([e1, e2], "All failed"); | Parameter | Description |
|---|---|
| message | Optional string explaining the problem (all Error types). |
| options.cause | Optional underlying error for chaining (modern engines). |
| errors (AggregateError) | Required iterable of errors collected together. |
| Return Value | Description |
|---|---|
| Error instance | An object with name, message, and usually stack. Throw it to report failure. |
| Type | When to use |
|---|---|
Error | General-purpose error. |
AggregateError | Wraps several errors (for example Promise.any). |
EvalError | Historical; rarely thrown by modern engines. |
RangeError | A number is outside the allowed range. |
ReferenceError | A variable does not exist. |
SyntaxError | Invalid code syntax (often from parsing). |
TypeError | Wrong type or invalid operation on a value. |
URIError | Bad URI component encoding/decoding. |
Wrong type of value.
try {
const x = null;
x();
} catch (err) {
console.log(err.name);
console.log(err instanceof TypeError);
} TypeError true
A number outside the allowed range.
try {
const arr = new Array(-1);
} catch (err) {
console.log(err.name);
} RangeError
Collect several errors in one object.
const err = new AggregateError(
[new Error("one"), new Error("two")],
"Both failed"
);
console.log(err.name);
console.log(err.errors.length);
console.log(err.message); AggregateError 2 Both failed
Learn toString and Error.isError next.
CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
8 people found this page helpful