JavaScript Error Types
JavaScript has several built-in error objects that represent different types of runtime errors. Understanding these types helps in debugging and handling exceptions effectively.
1. The Error Object
The Error object is the base type for all errors. It is also used for creating generic user-defined errors.
try {
throw new Error("Something went wrong!");
} catch (e) {
console.log(e.name); // "Error"
console.log(e.message); // "Something went wrong!"
}
2. Specific Error Types
SyntaxError
Occurs when the JavaScript engine encounters code that violates the language's syntax rules.
// SyntaxError: Unexpected token '}'
try {
eval("alert('Hello)"); // Missing closing quote
} catch (e) {
console.log(e.name); // "SyntaxError"
}
ReferenceError
Occurs when code attempts to access a variable that does not exist (has not been declared) in the current scope.
// ReferenceError: x is not defined
try {
x = y + 1;
} catch (e) {
console.log(e.name); // "ReferenceError"
}
TypeError
Occurs when a value is not of the expected type. This is very common when trying to access properties on undefined or null, or calling something that isn't a function.
// TypeError: num.toUpperCase is not a function
try {
const num = 123;
num.toUpperCase();
} catch (e) {
console.log(e.name); // "TypeError"
}
RangeError
Occurs when a value is not in the set or range of allowed values.
// RangeError: Invalid array length
try {
const arr = new Array(-1);
} catch (e) {
console.log(e.name); // "RangeError"
}
URIError
Occurs when global URI handling functions (like decodeURI or encodeURI) are used incorrectly.
// URIError: URI malformed
try {
decodeURI("%");
} catch (e) {
console.log(e.name); // "URIError"
}
EvalError
Represents an error regarding the global eval() function. This exception is not thrown by JavaScript anymore, but the object remains for backward compatibility.
3. Custom Errors
You can create custom error types by extending the Error class.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function readUser(json) {
const user = JSON.parse(json);
if (!user.age) {
throw new ValidationError("No field: age");
}
return user;
}
try {
readUser('{ "name": "John" }');
} catch (err) {
if (err instanceof ValidationError) {
console.log("Invalid data: " + err.message); // Invalid data: No field: age
} else {
throw err; // Unknown error, rethrow it
}
}
programming/javascript/vanilla/javascript programming/javascript/vanilla/error-handling