Skip to content

Instantly share code, notes, and snippets.

@leommoore
Last active December 11, 2015 01:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leommoore/4524381 to your computer and use it in GitHub Desktop.
Save leommoore/4524381 to your computer and use it in GitHub Desktop.
Node - Error Handling

#Node - Error Handling

##Uncaught Errors

var http = require('http');

http.createServer(function() {
  throw new Error('This will be uncaught');
}).listen(3000);

An error that is not handled is said to be uncaught. It leaves the process in an inconsitent state. We can catch and handle this error using:

process.on('uncaughtException', function (err) {
  console.error(err);
  process.exit(1); //manual exit
});

Note: Exit code 1 indicates an error, while exit code 0 indicates successful execution.

##Catching Error Events

try {
  var notValid = 10 / two; //two is undefined and will throw error
}
catch(e) {
  console.log(e.message);
}
finally {
  //Do cleanup
}

##Error Events Many Node.js native modules such as http and net will emit error events when an error occurs.

var net = require('net');

net.createServer(function(connection) {
  connection.on('error', function(err) {
    console.error(err); //err is an Error object
  }
}).listen(4000);

##Error Objects In addition, most of the asynchronous modules take a callback where the first parameter is either null or the error object. You can use this to determine if an error has happened and handle it accordingly.

var fs = require('fs');

fr.readFile('/etc/passwd', function(err, data) {
  if (err) return console.error(err);
  console.log(data);
});

Note: ```console.error()`` is used to log the error.

##Custom Error Objects You can also create your own Error objects.

var InvalidInputError = new Error('Invalid number input');

function inputNumber() {
  var input = Number(prompt('Please enter a number', ''));
  if (isNaN(input))
   throw InvalidInputError;
  return input;
}

try {
  alert(inputNumber() + 10);
  break;
}
catch(err) {
  if (err != InvalidInputError)
    throw err;
  alert('The input was not a valid input. Please try again.');
}

##Stack Traces When an error occurs, normally the stack srace is generated which show the execution sequence prior to the error event. Normally this is shown on STDOUT. It is also possible access the stack trace without an error using console.trace();. The error object also has a error.stack() method which shows the stack trace prior to the error.

function notDefined() {
  console.log('=========Stack Trace Before Error =========');
  console.trace();
  console.log('===========================================');
  try {
    someFunction();
  } catch (e) {
    console.error(e);
    console.log('=========Stack Trace After Error =========');
    console.log(e.stack());
  }
}

notDefined();

##JavaScript Error Objects There are a number of predefined error types in JavaScript.

  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment