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

snippet
// 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:

snippet
node error_example1.js
Node.js error example 1

Node.js Errors Example 2

File: timer2.js

snippet
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:

snippet
node error_example2.js
Node.js error example 2
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +