kharandziuk kharandziuk - 1 year ago 50
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) {
app.use('*', function(req, res) {
throw new Error()
supertest(app).get('/').expect(200, done)

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

Additional info:

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

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 Source

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) {

See Error Handling in express