Built-in error types
JavaScript defines several error types, all descendants of Error:
| Type | When it appears |
|---|---|
Error |
Generic error |
TypeError |
A value is not of the expected type (e.g. calling something that is not a function) |
RangeError |
A value is outside the allowed range |
SyntaxError |
Malformed code (e.g. invalid JSON) |
ReferenceError |
Using a variable that does not exist |
You can check the type with instanceof:
try {
null.method();
} catch (e) {
console.log(e instanceof TypeError); // true
}
Custom errors
For errors specific to your domain (for example, "insufficient balance"), create
a class that extends Error:
class InsufficientBalanceError extends Error {
constructor(message) {
super(message);
this.name = "InsufficientBalanceError";
}
}
throw new InsufficientBalanceError("You do not have enough balance");
This lets you tell your errors apart from the system ones and handle them
specifically in the catch.
Examples
A custom error
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
try {
throw new ValidationError("Required field");
} catch (e) {
console.log(e.name + ": " + e.message);
console.log("Is it an Error?", e instanceof Error);
}