Creating Custom Errors in JavaScript
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:
1 | class OutOfFuelError 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:
1 | try { |
Note that before you can handle a custom error, you need to explicitly throw the error in your code. For example:
1 | try { |
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:
1 | class OutOfFuelError extends Error { |
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.
tags: [“JavaScript”, “custom errors”, “error handling”]