Skip to content

Instantly share code, notes, and snippets.

@watson
Created October 9, 2012 04:52
Show Gist options
  • Save watson/3856687 to your computer and use it in GitHub Desktop.
Save watson/3856687 to your computer and use it in GitHub Desktop.
Gotchas when handling errors in the connect module
// This will break the program and exist to console with code 1
var connect = require('connect');
connect()
.use(function(req, res) {
setTimeout(function() {
// this is wrapped inside a setTimeout callback and will not get
// catched by the connect module. Instead node.js will see it as
// an uncaught exception and exist with code 1
throw new Error();
}, 0);
})
.listen(8080);
// This will break the program and exist to console with code 1
var connect = require('connect');
connect()
.use(function(req, res) {
req.on('end', function() {
// if expecting any input from the client, nested exceptions will
// NOT be caught by the connect module. Instead node.js will see
// it as an uncaught exception and exist with code 1
throw new Error();
});
})
.listen(8080);
// This will break the program and exist to console with code 1
var connect = require('connect');
connect()
.use(function() {
// this exception will be caught by the connect module and the stack-
// trace will be written to stdout. And a proper response will be written
// to the client.
throw new Error();
})
.use(function(err, req, res, next) {
// handle the catched error manually and exit the node app
if (err) {
console.log(err.stack);
process.exit(1);
}
})
.listen(8080);
// This will NOT break the program. Connect will catch the error
var connect = require('connect');
connect()
.use(function() {
// this exception will be caught by the connect module and the stack-
// trace will be written to stdout. And a proper response will be written
// to the client.
throw new Error();
})
.listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment