Node.js tutorial – error handling examples

The tutorial provides the detailing on the node.js errors being occurred while processing the application request. Node.js error could be node.js assertion errors, asynchronous API error, error-first callback, user-specified errors, syntax error, Eval error and Range error.

Like any other scripting language , the node.js error are also classified into the below given categories:

  • Standard Java Script Error : the below give errors can be considered as the node.js standard javaScript errors.
Error Name Error Description
<EvalError>depicts the error regarding the global eval() function
<syntaxError> depicts the error regrading the invalid syntax or code
<RangeError>depicts the error when the value is not set in the allow range value
<ReferenceError>depicts the error when a non-existent variable is referenced
<TypeError>depicts the error when the value is not of the expected type
<URIError>depicts the error when a global URI handling function returns processing error
Standard Java Script Error

Catch statement for Node.js SyntaxError

try {
  eval('evaluate something...');
} catch (e) {
  console.error(e instanceof SyntaxError); 
  console.error(e.message);                
  console.error(e.name);                   
  console.error(e.fileName);               
  console.error(e.lineNumber);             
  console.error(e.columnNumber);           
  console.error(e.stack);                  
}

Throw New Exception for EvalError

try {
  throw new EvalError('This is an EvalError Example', 'evalErrorFile.js', 21);
} catch (evalErrorException) {
  console.log(evalErrorException instanceof EvalError); // true
  console.log(evalErrorException.message);              // "This is an EvalError Example"
  console.log(evalErrorException.name);                 // "EvalError"
  console.log(evalErrorException.fileName);             // "evalErrorFile.js"
  console.log(evalErrorException.lineNumber);           // 21
}

Catch Statement for Node.js RangeError

function Validate(value)
{
    if(["Blue", "Red", "Grey"].includes(value) === false)
    {
        throw new RangeError('The user has entered the wrong vlaue:' + value)
    }
}
try
{
    check("Orange")
}
catch(error)
{
    if(error instanceof RangeError)
    {
        // code for range error handling
    }
}
  • System Error: The System error could occur when the node.js program / function performs the file open operation where the file does not exist or trying to send request data through the socket which is closed , then the node.js throws the system error
  • Assertion Error: These types of error are initiated by Node.js when defects an logic violation which is not expected due to processing the request. The node.js assert module raises the error.
  • User-specified Error: These types of errors are custom error written in the application code.

Error-first callbacks

The node.js asynchronous API methods follows the common pattern referred as “error-first-callback”. The error-first-callback pattern , a callback function is passed to the method as an argument. In case of error, the callback function is called with the Error Object as the first argument. In case of No Error, the first argument is passed as Null.

// Consider the example where customer file does not exist
const fs = require('fs');
function errorFirstCallback(err, data) {
  if (err) {
    console.error('Error Occured while processing the file data', err);
    return;
  }
  console.log(data);
}
fs.readFile('/directory/filefolder/customerFile', errorFirstCallback);

try catch failure for Asynchronous API methods

The node.js asynchronous API methods generated errors cannot be captured using the try…catch mechanism

const fs = require('fs');
try {
  fs.readFile('/directory/filefolder/customerFile', (err, data) => {
    if (err) {
      throw err;
    }
  });
} catch (err) {
  // This erorr block will not be processed for Asynchronous API methods
  console.error(err);
}