Skip to content

Instantly share code, notes, and snippets.

@machadogj
Created April 5, 2013 20:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save machadogj/5322588 to your computer and use it in GitHub Desktop.
Save machadogj/5322588 to your computer and use it in GitHub Desktop.
Sample code for understanding error handling in node.js.
process.on('uncaughtException', function ( err ) {
console.error('An uncaughtException was found, the program will end.');
//hopefully do some logging.
process.exit(1);
});
try
{
setTimeout(function () {
throw new Error('who will catch me?');
}, 1);
}
catch (e) {
console.log('not me');
}
var util = require('util'),
EventEmitter = require('events').EventEmitter;
var MyClass = function () {
if (!(this instanceof MyClass)) return new MyClass();
EventEmitter.call(this);
};
util.inherits(MyClass, EventEmitter);
try
{
setTimeout(function () {
throw new Error('who will catch me?');
}, 1);
}
catch (e) {
console.log('not me');
}
app.get('/', function ( req, res, next ) {
getSomething(function ( err, data ) {
if ( err ) {
var report = new Error('unable to get something in home');
report.status = 500;
report.inner = err;
next(report);
return;
}
if ( !data ) {
var report = new Error('something not found');
report.status = 404;
next(report);
return;
}
res.send(200, data);
})
});
var foo = new MyClass();
foo.on('error', function () { console.log('it blew')});
foo.emit('error');
var foo = new MyClass();
foo.emit('error');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment