# Node.js Error Handling

In 
Published 2022-12-03

This tutorial explains how the errors are handled in Node.js and also provides you with some examples.

When we are writing code, one of the important thing to know is how to handle errors.

In Node.js there are some techniques for handling errors:

  1. use the EventEmitter technique
  2. use the try catch block
  3. use the Promise technique
  4. use Continuation-Passing Style (CPS)

Here it is an example of using Continuation-Passing Style and try catch block:

var fs = require("fs");
console.log("");
 
//myFile4.txt DOES NOT exists, myFile1.txt DOES exists
 
// try ... catch bloc for exceptions/ errors
try {
  fs.readFileSync('myFile4.txt', function (err, data) {
    if (err) {
      return console.error('SYNC I -err: '+err);
    }
   
    console.log("11111 ");
    throw new Error('something bad happened');
    console.log("22222 ");
  });
  console.log("----------------------------------");
} catch (er) {
    console.log("From Catch = "+er);
    console.log("----------------------------------");
 }
 
// Error handeling in a procedure call
fs.stat('myFile4.txt', function (err, info) {
    if (err) {
        return console.error('Err1='+err);
        console.log('Err1='+err);
    }
 
    if (info) {
        console.log('is file (AA) = '+info.isFile());
    }
     
    console.log('is file (A) = '+info.isFile());
    
 });
 
 // if(info) in the middle of the procedure
 fs.stat('myFile1.txt', function (err, info) {
    if (err) {
        return console.error('Err2='+err);
        console.log('Err2='+err);
    }
 
    if (info) {
        console.log('is file (aa) = '+info.isFile());
    }
     
    console.log('is file (a) = '+info.isFile());
    
 });
 
 // if(info) at the END of the procedure
 fs.stat('myFile1.txt', function (err, info) {
    if (err) {
        return console.error('Err2='+err);
        console.log('Err2='+err);
    }
    
    console.log('is file (b) = '+info.isFile());
  
    if (info) {
        console.log('is file (bb) = '+info.isFile());
    }
 
 });

When you run the code you will see into the Console:

The execution log will show you how the errors are handling in Node.js.