Centralizing error handling in an express.js-based app Centralizing error handling in an express.js-based app express express

Centralizing error handling in an express.js-based app


You can use connect-domain middleware. It works with connect and express and based on Doman API.

You need to add connect-domain middleware as first middleware in stack. Thats all. Now you can throw errors everywhere in your async code and they will be handled with domain middleware and passed to express error handler.

Simple example:

// Some async function that can throw errorvar asyncFunction = function(callback) {    process.nextTick(function() {        if (Math.random() > 0.5) {            throw new Error('Some error');        }        callback();    });};var express = require('express');var connectDomain = require('connect-domain');var app = express();app.use(connectDomain());// We need to add router middleware before custom error handlerapp.use(app.router);// Common error handler (all errors will be passed here)app.use(function(err, req, res, next){    console.error(err.stack);    res.send(500, 'Something broke!');});app.listen(3131);// Simple routeapp.get('/', function(req, res, next) {    asyncFunction(function() {        res.send(200, 'OK');    });});