Node.js Errors

The Node.js applications generally face four types of errors:

  • Standard JavaScript errors i.e. <EvalError>, <SyntaxError>, <RangeError>, <ReferenceError>, <TypeError>, <URIError> etc.
  • System errors
  • User-specified errors
  • Assertion errors

Node.js Errors Example 1

Let’s take an example to deploy standard JavaScript error – ReferenceError.

File: error_example1.js

// Throws with a ReferenceError because b is undefined  

try {  

  const a = 1;  

  const c = a + b;  

} catch (err) {  

  console.log(err);  

} 

    Open Node.js command prompt and run the following code:

    node error_example1.js  
    Node.js error example 1

    Node.js Errors Example 2

    File: timer2.js

    const fs = require('fs');  
    
    function nodeStyleCallback(err, data) {  
    
     if (err) {  
    
       console.error('There was an error', err);  
    
       return;  
    
     }  
    
     console.log(data);  
    
    }  
    
    fs.readFile('/some/file/that/does-not-exist', nodeStyleCallback);  
    
    fs.readFile('/some/file/that/does-exist', nodeStyleCallback); 

      Open Node.js command prompt and run the following code:

      node error_example2.js  
      Node.js error example 2

      Comments

      Leave a Reply

      Your email address will not be published. Required fields are marked *