Node.js — Create Your Own Custom Error

Code Sample

Handling errors plays a major role in your application. In error situations, you want to know the details of the issue and how to solve it. When developing your app, you can create your own errors.

Errors in Node.js are extensible classes. This tutorial walks you through the creation of your own error class.

Node.js Series Overview

Create an Error Class

Node.js comes with an Error class. This error class gives you the core functionality of errors, like capturing a stack trace and assigning context data.

You can extend Node’s error class to create your own errors. Here’s an example of a NotEnoughCoffee error:

error.js

class NotEnoughCoffee extends Error {  
  constructor (message) {
    super(message)

    this.name = this.constructor.name
  }
}

module.exports = NotEnoughCoffee  

The custom error extends the default Node.js error class. Setting the this.name property to the constructor’s name will reference NotEnoughCoffee in stack traces instead of the generic Error name.

Go ahead and add other class properties when needed. You can even add methods of that is more helpful. Here’s an example:

class CoffeeNotFound extends Error {  
  constructor (message) {
    super(message)

    this.name = this.constructor.name
    this.status = 404
  }

  statusCode() {
    return this.status
  }
}

module.exports = CoffeeNotFound  

This CoffeeNotFound error could be an HTTP error. You may intercept the response and map the error’s status to the HTTP response status.

Throwing Errors

Import the custom error in your app and use it when necessary. Here’s a simple example that just throws the NotEnoughCoffee error:

'use strict'

const NotEnoughCoffee = require('./error')

throw new NotEnoughCoffee('Well, you may need another coffee :)')  

The related error output on your terminal looks like this:

Stack trace when throwing the NotEnoughCoffee error

Custom errors are a good way to help your coworkers and other developers to know what’s wrong with the app configuration.

Enjoy coding & make it rock!

Explore the Library

Find interesting tutorials and solutions for your problems.