Building an error handling system using NodeJS

Tram Ho

Translated from the source

Troubleshooting isn’t just about reducing developer time to find bugs, it’s about building a codebase that scales with your system.

Error Types in NodeJS

In Node.js there are 2 main types of errors:

  • Operational errors : runtime error, some examples: “Out of memory”, “An invalid input for an API endpoint”
  • Programmer errors : unexpected bugs, the code itself has problems to solve. Typical example: reading the property of “undefined” object. These bugs are often created by devs and not related to operations.

Error handling

With the errors already defined by Node.js, it is easy to track the information around it thanks to Stacktrace → from which we can find the root cause of the error.

In addition, extending from Error class as well as adding other properties such as HTTP status code will also help information about errors become more detailed.

Some basic httpStatusCode can be added here:

Usage is as follows:

Centralized error handling with NodeJS

Building a component with functionality to handle errors will help reduce the amount of duplication of error handling code in the project. This component is responsible for making catching errors easier to understand for example:

  • Send notification to system admin
  • Pass error events to a monitoring service like Sentry.io and log them out

File_000

Before being sent to error-handling centralized, errors are sent to error-handling middleware to phân biệt giữa các error types .

And Error-handling centralized would look like this:

To make it easier for developers to track bugs, log errors out in an easy-to-see format.

Some typical formatter loggers are:

These two libraries will help provide logs in different level formats depending on the level of the error.

With Programmer errors , the best solution is B1. Crash app instantly B2. Restart the app with tools like pm2

This is because Programmer errors will often cause the app to end up in an unexpected state.


With offers rejection we can do the following:
Share the news now

Source : Viblo