Types of Errors
JavaScript has several built-in error types. Understanding them helps you write better error handling and debug faster. Each error type has a specific name that tells you what went wrong.
// ReferenceError — using a variable that doesn't exists
console.log(x); // ReferenceError: x is not defined
// TypeError — wrong type of operation
null.foo(); // TypeError: Cannot read properties of null
// SyntaxError — code that can't be parsed
eval("function("); // SyntaxError
// RangeError — value outside allowed range
const arr = new Array(-1); // RangeError
// URIError — malformed URI
decodeURI("%"); // URIError
Catching Specific Errors
You can check the error type inside a catch block and handle each one differently.
try {
JSON.parse("not json");
} catch (error) {
if (error instanceof SyntaxError) {
console.log("Invalid JSON format");
} else {
console.log("Something else went wrong");
}
}
Creating Custom Error Types
You can extend the built-in Error class to create your own error types. This makes your code more readable and easier to debug.
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function validateAge(age) {
if (age < 0 || age > 150) {
throw new ValidationError("Invalid age", "age");
}
}
Try it Yourself →
Error Properties
Every error object has useful properties like name, message, and stack. The stack trace shows you exactly where the error occurred.
try {
undefinedFunction();
} catch (error) {
console.log(error.name); // "ReferenceError"
console.log(error.message); // "undefinedFunction is not defined"
console.log(error.stack); // Full stack trace
}
Summary
Knowing the different error types helps you handle errors gracefully. Use instanceof to check error types, and create custom error classes for domain-specific validation.