Created
August 12, 2011 06:28
-
-
Save samyakbhuta/1141573 to your computer and use it in GitHub Desktop.
Catching an uncaughtException in express.js based server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
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
// 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 );
});