Error objects
Error objects in JavaScript are objects that contain information about an error that has occurred during the execution of your code. They are typically generated when an exception is thrown and can provide useful information for debugging and error handling.
In JavaScript, there are several types of built-in error objects that inherit from the Error object:
Error: The base error object from which all other errors inherit. It contains a message property that describes the error.
SyntaxError: An error that occurs when there is a syntax error in the code (e.g., a missing semicolon).
ReferenceError: An error that occurs when an undefined variable or function is referenced.
TypeError: An error that occurs when a value is not of the expected type (e.g., calling a method on a null or undefined value).
RangeError: An error that occurs when a value is outside the expected range (e.g., creating an array with a negative length).
URIError: An error that occurs when a URI-related function is used incorrectly.
Here's an example of how to create and throw a built-in error object:
try {
let x;
console.log(x.toUpperCase());
} catch (error) {
if (error instanceof TypeError) {
console.log("A type error occurred: " + error.message);
} else {
console.log("An error occurred: " + error.message);
}
}
In this example, we catch the error that is thrown when we try to call the toUpperCase() method on an undefined variable x. We check if the error is an instance of the TypeError object, and if it is, we log a custom message to the console. Otherwise, we log a generic error message with the error message property.
You can also create your own custom error objects by extending the built-in Error object or by creating a new object with a message property. Custom error objects can provide more specific information about the error and can be useful for handling errors in a more structured way in your code.