×

Node.js Error Handling

Node.js – Error Handling: Errors are part of every programming language, and Node.js Environment is not an exception. There are many predefined errors in Node.js, including errors like SyntaxError, RangeError, and many more. The official documentation of Node.js has provided a detailed description of the Errors. However, the point to be noted is that this documentation also refers to the Exceptions. So, let just not be confused with Errors over Exceptions.

Exceptions are the values thrown as the Output of the Invalid Operations or as the throw statements' targets. Therefore, all exceptions thrown by the JavaScript runtime or Node.js will be the instances of Errors. Thus, we will be handling errors as exceptions in Node.js.

Understanding the Types of Errors in Node.js

Firstly, it is essential to have a clear understanding of errors in Node.js. Generally, the errors in Node.js are classified into two different categories. The First one is Operational errors, and the other is Programmer errors, respectively.

  • Operational errors: The Operational errors represent the problems with runtime whose outputs are predictable and should be dealt appropriately. Operational errors do not mean that the application itself has bugs but indicates that developers must carefully handle these errors. For Example, the operational errors include "an invalid input for an API endpoint", "out of memory", and many more.
  • Programmer errors: The Programmer errors represent the unexpected bugs in code that are written poorly. The Programmer errors indicate that the application itself has some unsolved issues, and codes are miswritten. For Example, calling an asynchronous function without a callback or trying to read the "undefined" property. To fix the issue, the syntax has to be modified or changed. The developer makes this bug; thus, it is not an operational error.

To Understand the concept of Error Handling, let's start with creating exceptions.

Creating Exceptions

To create an exception, we use the 'throw' keyword following the value:

throw value;

Once JavaScript executes the above line, the normal flow of the program stops, and the control is held back to the closest exception handler. Any JavaScript value used as the client-side code value can be a number, a string, or an object.

Note: Generally, we throw Error objects in Node.js instead of throwing any strings.

Error objects

Error objects capture a "stack trace" specifying the point in the code at which the Error was instantiated and may give a text description of the Error.

All the errors created by Node.js, including JavaScript and all system errors, will either be inherited from or instances of the Error class provided in the Error core module:

throw new Error(‘The Access is Denied’);

or

class AccessIsDeniedError extends Error {
    //...
  };
  throw new AccessIsDeniedError();

Handling Exceptions

The try/catch statement is used as an exception handler. The corresponding catch block handles any exception that appear

s in the code line's syntax comprised in the try block.

try {
    // the lines of code
  } catch (ExceptionValue) {};

To catch various types of errors, we can add multiple handlers.

Catching the Uncaught Exceptions

The program will crash if an uncaught exception gets thrown when the program is being executed. The uncaughtException event is used in the process object to solve such a situation.

process.on('uncaughtException', err => {
    console.error('Uncaught error has been reported!', err);
    process.exit(1) // required (as per the docs of Node.js)
  });

We don't have to import the built-in process module for the procedure, as it's injected automatically.

Exceptions using promises

We can use promises to chain different operations and handle the errors at the end:

doOperation1()
  .then(doOperation2)
  .then(doOperation3)
  .catch(err => console.error(err))

So, a question pops up in one's head is: How do we know where the Error occurred? Well, we don't know, but whenever we call (doOperationX), we can handle errors in each of the functions and can be called outside of the catch handler by throwing a new error in the error handler:

const doOperation1 = () => {
    //...
    try {
      //...
    } catch (err) {
      //... handling the error locally
      throw new Error(err.message)
    };
    //...
  };

We can break the chain without handling the errors in the function we call but, locally, we can process the exception by creating a function in each then():

doOperation1()
  .then(() => {
    return doOperation2().catch(err => {
      // error handling
      throw err; // breaking the chain!
    });
  })
  .then(() => {
    return doOperation2().catch(err => {
      // error handling
      throw err; // breaking the chain!
    });
  })
  .catch(err => console.error(err));

Handling Error using async/await

We still need to catch errors while using async/await in the following manner:

async function someOperation() {
    try {
      await someOtherOperation()
    } catch (err) {
      console.error(err.message);
    }
  };

Related Topics

Node.js Modules

Node.js Modules: At the point when we'll begin composing Node.js applications, we would place all our code into one big node.js file, regardless of how enormous or complex our application...

4 minutes read.

Node.js Discovering Timers

Node.js Discovering Timers: Timers are multi-lingual, and much functional in countless use cases. The Timers are mostly used in many popular programming languages, including Node.js. However, it's pretty simple to...

4 minutes read.

Node.js Error Handling

Node.js – Error Handling: Errors are part of every programming language, and Node.js Environment is not an exception. There are many predefined errors in Node.js, including errors like SyntaxError, RangeError, and...

4 minutes read.

Difference Between Node.js and PHP

Node.js vs PHP Node.js and PHP both are the powerful back-ends to create versatile websites. Even when these two technologies fall under the same category, their features are pretty diverse. There's...

6 minutes read.

Node.js NPM

Node.js – Node Package Manager NPM is an abbreviation for Node Package Manager. It is the default package manager developed by Isaac Z. Schlueter using JavaScript Programming Language, designed for JavaScript Runtime...

7 minutes read.

Node.js Event Loop

An Introduction to Event Loop As we have already discussed, Node.js is an Asynchronous platform with a non-blocking I/O. Node.js has awesome features that made it this thriving, and the Event...

5 minutes read.

Node.js Core Debugger

Node.js – Core Debugger: It’s always a challenge when it comes to debug an application. The Asynchronous workflows of Node.js include an additional layer of intricacy to this difficult process....

3 minutes read.

Node.js OS Module

Introduction to Node.js OS Module The OS Module in Node.js provides the Operating System-related Utilities. This module delivers the functions to interact with the Operating System. It also delivers the Operating...

5 minutes read.

Node.js Path Module

Understanding the path Module in Node.js The path module is a built-in module of Node.js that provides various methods to interact with the files and directory path names on the device’s...

6 minutes read.

Node.js Event Loop Phases

Node.js – Phases of Event Loop Once we have understood the Node.js event loop concept and the basic introduction to its phases, let's discuss the functions of the Check handler phase...

4 minutes read.

Node.js Buffers

An Introduction to Buffers A Buffer is an area in memory (typically RAM) that is used to store binary data. Binary is a collection or a set of 0 and 1....

4 minutes read.

Node.js REPL

Node.js REPL: REPL represents the Read Eval Print Loop. REPL is modest; much more, an interactive software development environment similar to the command line shells used in various Operating Systems....

4 minutes read.

Node.js Events Module

Introduction to the Node.js events Module As we’ve already discussed, Node.js is a JavaScript runtime with an event-driven architecture designed to perform Asynchronous tasks. In order to accomplish the event-driven architecture,...

4 minutes read.

How to Install Node.js on Windows?

Environment Setup for Node.js Since Node.js is a mandatory section of the program that runs JavaScript, similar to all other required section of programs that run a programming language, it is...

4 minutes read.

Node.js HTTP Module

An Introduction to HTTP Module The http module is a core module in Node.js that uses the Hypertext Transfer Protocol (HTTP) to transfer data. With the help of the http module,...

7 minutes read.

Node.js Tutorial

Introduction to Node.js: Node.js is a non-proprietary and platform-independent runtime environment for implementing JavaScript code outside of a browser. However, NodeJS isn't a framework and not a programming language. We...

4 minutes read.

Node.js Callback Concept

Understanding the Concept of Callback A Callback is an asynchronous equivalent for a function that is called at the completion of a task. The Callback helps to avoid any I/O blocking and allows other code to execute...

2 minutes read.

Difference Between Nodejs Angular and React

A Right JavaScript Framework Within a business, it is necessary to pick the right technology. As much as this applies to the web application and software development, it also applies in...

5 minutes read.

Differentiation of Web Scraping and Web Crawling

Most of us get confused between the word’s web scraping and web crawling, and even some people think they are synonyms for each other. But there is a considerable difference between...

3 minutes read.

Node.js Streams

An Introduction to the Streams Streams are one of the elemental concepts that are introduced to power the applications based on Node.js. These are the method used to handle the data...

6 minutes read.