Skip to content

Instantly share code, notes, and snippets.

@samyakbhuta
Created August 12, 2011 06:28
Show Gist options
  • Save samyakbhuta/1141573 to your computer and use it in GitHub Desktop.
Save samyakbhuta/1141573 to your computer and use it in GitHub Desktop.
Catching an uncaughtException in express.js based server
var express = require('express');
process.on('uncaughtException', function(err) {
console.log( " UNCAUGHT EXCEPTION " );
console.log( "[Inside 'uncaughtException' event] " + err.stack || err.message );
});
anHTTPServer = express.createServer(function (req,res){
if (Math.random() > 0.9) throw new Error('fail!');
res.send("Hello World : Express!!");
});
anHTTPServer.listen(3000);
@samyakbhuta
Copy link
Author

var express = require('express');

anHTTPServer = express.createServer(function (req,res){
if (Math.random() > 0.9) throw new Error('fail!');
res.send("Hello World : Express!!");
});

anHTTPServer.listen(3000);

if (Math.random() > 0.5) throw new Error('fail!');

process.on('uncaughtException', function (err) {
console.log( "UNCAUGHT EXCEPTION " );
console.log( "[Inside 'uncaughtException' event] " + err.stack || err.message );
});

@samyakbhuta
Copy link
Author

// To have control of both kinda errors, ones inside express.js and othewise.
// For catching express errors, use anHTTPServer.error(...). IMPORTANT : If you don't put this, errors generated inside express will still be not caught using process.on('uncaughtException', function (err) {...}
// For anything else just use process.on('uncaughtException', function (err) {...}
var express = require('express');

anHTTPServer = express.createServer(function (req,res){
if (Math.random() > 0.9) throw new Error('Failed, 90:10');
res.send("Hello World : Express!!");
});

anHTTPServer.listen(3000);

anHTTPServer.error(function(err, req, res, next){
console.log( "[anHTTPServer.error(...) called !] " +err.stack || err.message);
});

if (Math.random() > 0.5) throw new Error('Failed, 50:50');

process.on('uncaughtException', function (err) {
console.log( "UNCAUGHT EXCEPTION " );
console.log( "[Inside 'uncaughtException' event] " + err.stack || err.message );
});

@alvaropaco
Copy link

You have a problem with this approach. Basically, is a exception occurs and you catch this on your proccess.on you will perform the callback to any other requests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment