Throwing and handling custom errors
In addition to the built-in errors in JavaScript, you can also create and throw your own custom errors. This can be useful when you need to handle specific cases in your application that are not covered by the standard errors.
Here's an example of how to create and throw a custom error:
class MyError extends Error {
constructor(message) {
super(message);
this.name = "MyError";
}
}
throw new MyError("Something went wrong");
In this example, we create a custom error class called MyError that extends the built-in Error class. The constructor method takes a message parameter, which is passed to the parent Error constructor using the super keyword. We also set the name property to "MyError" to make it easier to identify the error later.
To throw the custom error, we simply use the throw keyword followed by a new instance of the MyError class. This will generate an error with the message "Something went wrong" and the name "MyError".
To handle a custom error, you can use a try-catch statement just like with the built-in errors:
try {
// Code that might throw a custom error
} catch (error) {
if (error instanceof MyError) {
console.log("A MyError occurred: " + error.message);
} else {
console.log("An error occurred: " + error.message);
}
}
In this example, we check if the error that was caught is an instance of the MyError class using the instanceof operator. If it is, we log a custom message to the console. If it's not, we log a generic error message.
Custom errors can be useful for creating more specific error messages and handling errors in a more structured way in your code.