Custom errors are created to give more information about what exactly has gone wrong in an application. They are created using the error constructor. An example of a custom error could be RecordNotFoundError, ValidationError, FormatError, etc
Why the error constructor ?
An error can basically be thrown by just throwing a new instance of an error object with a custom message.
In the code above, the function checkStatus checks if any user data provided as argument has emailConfirmed property set to true. Else, it throws an error.
In as much as the code above throws a runtime error when by creating an instance of the error object, it limits the having properties or methods on the instance to provide other useful information.
In the code above, a class Validation Error is created to extend the Error object. Aside the standard message property on the Error object, through creating the validation Error class we are able to access(or create) other properties like the code.
Hence the advantages of creating a custom error object by extending the error object includes:
- Create specific errors whenever a runtime error is occured.
- Creating properties or methods on the custom error object.
- Extending the error contractor gives access to the stackTrace which gives information of exact location of error.