DEV Community

Cover image for Custom Errors in JavaScript

Posted on

Custom Errors in JavaScript

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.
For instance

code explains custom error. Text explanation below image

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.

For instance

extending the Error object to create a custom error

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:

  1. Create specific errors whenever a runtime error is occured.
  2. Creating properties or methods on the custom error object.
  3. Extending the error contractor gives access to the stackTrace which gives information of exact location of error.


Top comments (1)

kofiasare profile image
Kofi Asare

Good one.