Node.js — Create Your Own Custom Error

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

  1. Callback and Promise Support in your Node.js Modules
  2. Increase the Memory Limit for Your Process
  3. Why You Should Add “node” in Your Travis Config
  4. How to Run an Asynchronous Function in Array.map()
  5. Create a PDF from HTML with Puppeteer and Handlebars
  6. Get Number of Seconds Since Epoch in JavaScript (Coming soon)
  7. Create Your Own Custom Error
  8. Extend Multiple Classes (Multi Inheritance) (Coming soon)
  9. Filter Data in Streams (Coming soon)
  10. Get a File’s Created Date (Coming soon)
  11. Get a File’s Last Modified/Updated Date (Coming soon)
  12. How to Reset and Empty an Array (Coming soon)
  13. Human-Readable JSON.stringify() With Spaces and Line Breaks (Coming soon)
  14. String Replace All Appearances (Coming soon)
  15. Write a JSON Object to a File (Coming soon)

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.