0

I have this simple code. This must show me my error object ({error:'error'}) upon each request. But it shows only "[Object object]". And moreover - debugger never stops in the error handler function. What is going on?

var domain = require('domain');
var express = require('express');
var server = express();

server.get('/', function(req, res)
{
    var d = domain.create();
    d.on('error', function(e)
    {
        debugger;
        console.log(JSON.stringify(e));
    }); 

    d.run(function()
    { 
        throw {error:'error'};
        res.send('ok');
    });
});

server.listen(8080);
Andrey Kon
  • 747
  • 2
  • 6
  • 16

1 Answers1

0

The problem is that domains catch the error all the way at the bottom of the call stack, and since express has its own error handling code, the error gets caught by express before reaching the domain. Similar issue here: Node.js - Domain per Express request, inside another domain

I don't see any particularly good reason it should be this way, but that's how the code seems to work [1] (source here: https://github.com/joyent/node/blob/master/lib/domain.js). Possible workarounds are to surround the d.run() call with your own try/catch, or to do something like

d.run(process.nextTick(function() {
   // do stuff
}));

[1] The way domains work is that they basically hook into all of the "asynchronous" callbacks and add some information that records who initiated the asynchronous operation. I don't know why they don't also try/catch on the initial synchronous block.

Community
  • 1
  • 1
arghbleargh
  • 3,090
  • 21
  • 13
  • Well, this sounds very weird to me and needs more investigation. The point is that in many other cases similar constructions inside expressjs requests somehow worked for me and domains were catching errors perfectly. I just havent't managed yet to track down the patterns when thyey worked and when they didn't so as to understand where the problem is. – Andrey Kon Nov 04 '14 at 08:23
  • Wow, I've just managed to find out that my domain starts catching the errors once the code is wrapped inside any other callback, not only process.nextTicket(), but even fs.exists()! – Andrey Kon Nov 04 '14 at 08:33
  • http://stackoverflow.com/questions/13228649/unable-to-handle-exception-with-node-js-domains-using-express – Andrey Kon Nov 04 '14 at 08:47