DEV Community

loading...
Cover image for Custom Errors in JavaScript

Custom Errors in JavaScript

grena_me
・2 min read

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.

Reference:
https://medium.com/@xjamundx/custom-javascript-errors-in-es6-aa891b173f87
https://javascript.info/custom-errors
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

Discussion (1)

Collapse
kofiasare profile image
Kofi Asare

Good one.