kharandziuk kharandziuk - 4 months ago 13
Node.js Question

Express.js 4 and domain module: why domain doesn't handle the error?

I'm trying to familiarize myself with domain module. So, I created a study sample below:

var express = require('express')
var domain = require('domain')
var supertest = require('supertest')

describe('some', function() {
it('some', function(done) {
var app = express()
app.use(function(req, res, next) {
var d = domain.create();
d.on('error', function(e) {
console.log('here')
});
d.run(next)
})
app.use('*', function(req, res) {
throw new Error()
res.end()
})
supertest(app).get('/').expect(200, done)
})
})


But, it doesn't work as I expected. Can somebody explain why it never reaches
error
callback?

Additional info:

$ npm list --depth=0
├── express@4.13.4
├── mocha@2.4.5
└── supertest@1.2.0
$ node -v
v6.0.0


P.S.: it's deprecated, I know. But on the moment there is no alternatives and large codebase of projects which actually use it

Answer

The reason is that Express 4 is doing exception handling before your code with domain works, you can make sure that I am correct by adding following handler on bottom, it kinda wraps everything in try/catch and if there is no error handler prints error stack:

app.use(function (err, req, res, next) {
   console.log(err);
   res.end();
});

See Error Handling in express

Comments