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:


class NotEnoughCoffee extends Error {  
  constructor (message) {

    // assign the error class name in your custom error (as a shortcut) =

    // capturing the stack trace keeps the reference to your error class
    Error.captureStackTrace(this, this.constructor);

    // you may also assign additional properties to your error
    this.isSleepy = true

module.exports = NotEnoughCoffee  

The custom error extends the default Node.js error class. Setting the 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 that are more helpful. Here’s an example:

class CoffeeNotFound extends Error {  
  constructor (message) {
    Error.captureStackTrace(this, this.constructor); =
    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.