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
- Callback and Promise Support in your Node.js Modules
- Increase the Memory Limit for Your Process
- Why You Should Add “node” in Your Travis Config
- How to Run an Asynchronous Function in Array.map()
- Create a PDF from HTML with Puppeteer and Handlebars
- Get Number of Seconds Since Epoch in JavaScript (Coming soon)
- Create Your Own Custom Error
- Extend Multiple Classes (Multi Inheritance) (Coming soon)
- Filter Data in Streams (Coming soon)
- Get a File’s Created Date (Coming soon)
- Get a File’s Last Modified/Updated Date (Coming soon)
- How to Reset and Empty an Array (Coming soon)
- Human-Readable JSON.stringify() With Spaces and Line Breaks (Coming soon)
- String Replace All Appearances (Coming soon)
- 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:
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!