Error
Error is a built-in object that represents runtime errors. It serves as the base constructor for all JavaScript errors, including built-in error types like TypeError, RangeError, SyntaxError, and ReferenceError.
Creating Error Instances
Create an Error using the new keyword with the Error constructor:
const error = new Error("Something went wrong");
// Error: Something went wrong
// You can also call it without new (works the same way)
const error2 = Error("Another error");
// Error: Another error
The Error constructor accepts two parameters:
message: A human-readable description of the erroroptions: An object with acauseproperty (ES2022+)
const error = new Error("Failed to load", { cause: "NETWORK_ERROR" });
// Error: Failed to load
// error.cause === "NETWORK_ERROR"
Error Properties
Each Error instance has useful properties:
const error = new Error("Test error");
error.message // "Test error"
error.name // "Error"
error.stack // Full stack trace (non-standard but widely supported)
error.cause // The underlying cause (ES2022+)
Built-in Error Subtypes
JavaScript provides several built-in error constructors that inherit from Error:
TypeError
Thrown when a value is not of the expected type:
const fn = "hello";
fn(); // TypeError: fn is not a function
RangeError
Thrown when a value is outside an allowed range:
const arr = new Array(-1); // RangeError: Invalid array length
SyntaxError
Thrown when parsing invalid JavaScript syntax:
eval("const x ="); // SyntaxError: Unexpected token
ReferenceError
Thrown when accessing an undefined variable:
console.log(undefinedVar); // ReferenceError: undefinedVar is not defined
URIError
Thrown when URI handling functions are used incorrectly:
decodeURIComponent("%"); // URIError: URI malformed
Throwing Errors
Use throw to raise errors:
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
divide(10, 0);
} catch (e) {
console.log(e.message); // "Cannot divide by zero"
console.log(e instanceof Error); // true
}
Extending Error
Create custom error types by extending Error:
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
const err = new ValidationError("Invalid email", "email");
console.log(err instanceof Error); // true
console.log(err instanceof ValidationError); // true
Error Handling Best Practices
Always Catch Specific Errors
try {
riskyOperation();
} catch (e) {
if (e instanceof TypeError) {
// Handle type error specifically
} else if (e instanceof RangeError) {
// Handle range error
} else {
// Handle unknown errors
throw e;
}
}
Re-throw with Context
try {
await fetchData();
} catch (e) {
throw new Error("Failed to fetch data", { cause: e });
}
Check Error Types Without Catching
function isErrorLike(value) {
return value instanceof Error ||
(value && typeof value.message === "string" && typeof value.name === "string");
}