Skip to content

Instantly share code, notes, and snippets.

@sthawali
Last active December 23, 2015 10:19
Show Gist options
  • Save sthawali/6620852 to your computer and use it in GitHub Desktop.
Save sthawali/6620852 to your computer and use it in GitHub Desktop.
Handle error globally in express.js app
var express = require('express');
var http = require('http');
var app = express();
app.use(
function handleError(req, res, next) {
var domain = require('domain').create();
res.on('close', function() {
domain.dispose();
});
domain.on('error', function(error) {
// Caught error.
// Deal with error here.
domain.dispose();
next(error);
});
domain.run(next);
}
);
app.get('/', function(req, res) {
a+b; // Throw an error!
res.setHeader("Content-Type", "text/plain");
res.end("WOHOO! Everything is fine!");
});
app.all('*', function(error, req, res, next) {
res.writeHeader(500, {'Content-Type' : "text/html"});
res.write("<h1>" + error.name + "</h1>");
res.end("<p style='border:1px dotted red'>" + error.message + "</p>");
});
http.createServer(app).listen(5678, function() {
console.log("Server is running on port 5678");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment