Types of Errors, Error Codes in JavaScript
Sraban Pahadasingh June 25, 2024 12:48 AMJavaScript has several built-in error types that help in identifying and handling different kinds of errors. Here are some common error types:
SyntaxError
Occurs when there is a syntax issue in the code.
- Example:
console.log('Hello; // Missing closing quote
ReferenceError
Occurs when a non-existent variable is referenced.
- Example:
console.log(nonExistentVariable); // ReferenceError
TypeError
Occurs when a value is not of the expected type.
- Example:
null.foo(); // TypeError: Cannot read property 'foo' of null
RangeError
Occurs when a value is not within the set or acceptable range.
- Example:
new Array(-1); // RangeError: Invalid array length
EvalError
Occurs when the eval()
function is used incorrectly. It's rarely encountered because eval()
is discouraged.
- Example:
eval('foo)'); // SyntaxError: Unexpected token
URIError
Occurs when there is an error in encoding or decoding URIs.
- Example:
decodeURIComponent('%'); // URIError: URI malformed
Error Codes
Custom errors can be created with specific codes to handle specific conditions.
- Example:
class CustomError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
throw new CustomError('Custom error message', 'E_CUSTOM');