NodeJS - Exception Handling in Asynchronous Code


An exception is a type of an event that occurs while executing or running a program that stops the normal flow of the program and returns to the system. When an exception occurs the method creates an object and gives it to the runtime system. This creating an exception and giving it to the runtime system is known as throwing an Exception.

We need to handle these Exceptions to handle any use case and prevent the system from crashing or performing an unprecedented set of instructions. If we donot handle or throw exceptions, the program may perform strangely.

Exception handling in Asynchronous Program

Here, we will learn how to handle exceptions in an asynchronous flow of program. Asynchronous code is also known as a callback-based code. It basically gives a temporary response stating request received or In progress o state that its working further. After the processing is done, it gives back a callback with the final response to the desired system.

Callback has an argument as err. This argument holds the error if any error occurs while computation, else err will be null.

Example

// Define a divide program as a syncrhonous function
var divideNumber = function(x, y, next) {
   // if error condition?
   if ( y === 0 ) {
      // Will "throw" an error safely by returning it
      // If we donot throw an error here, it will throw an exception
      next(new Error("Can not divide by zero"))
   } else {
      // If noo error occurred, returning error as null
      next(null, x/y)
   }
}

// Divide 10 by 5
divideNumber(10, 5, function(err, result) {
   if (err) {
      // Handling the error if it occurs...
      console.log("10/5=err", err)
   } else {
      // Returning the result if no error occurs
      console.log("10/5="+result)
   }
})

// Divide 10 by 0
divideNumber(10, 0, function(err, result) {
   // Checking if an Error occurs ?
   if (err) {
      // Handling the error if it occurs...
      console.log("10/0=err", err)
   } else {
      // Returning the result if no error occurs
      console.log("10/0="+result)
   }
})

Output

Updated on: 28-Apr-2021

160 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements