JavaScript provides a set of 8 error objects that are raised in a try/catch expression based on the type of error encountered. These error objects are:
ErrorEvalErrorRangeErrorReferenceErrorSyntaxErrorTypeErrorURIError
If you want to create your own custom errors in JavaScript, you can extend the base Error class. This allows you to handle different error types in a specific way, without relying solely on error messages to determine the type of error.
To create a custom error, you can define a new class that extends the Error class. Here’s an example:
class OutOfFuelError extends Error {}
class FlatTireError extends Error {}
Once you have defined your custom error classes, you can handle them in a try/catch block by checking the instance of the error. Here’s an example:
try {
// some code
} catch (err) {
if (err instanceof OutOfFuelError) {
// handle OutOfFuelError
} else if (err instanceof FlatTireError) {
// handle FlatTireError
}
}
Note that before you can handle a custom error, you need to explicitly throw the error in your code. For example:
try {
const car = new Car(); // imagine we have a Car object
if (!car.fuel) {
throw new OutOfFuelError('No fuel!');
}
if (car.flatTire) {
throw new FlatTireError('Flat tire!');
}
} catch (err) {
if (err instanceof OutOfFuelError) {
// handle OutOfFuelError
} else if (err instanceof FlatTireError) {
// handle FlatTireError
}
}
When creating a custom error, you can also customize aspects of the class, including the parameters received by the constructor if needed. Here’s an example:
class OutOfFuelError extends Error {
constructor(message) {
super(message);
this.name = "OutOfFuelError";
}
}
In conclusion, creating custom errors in JavaScript allows you to handle different error types in a more specific and controlled manner. By extending the base Error class, you can define your own error classes and handle them accordingly in your code.