Unable to handle exception with node.js domains using express
@user1007983
No, in production, the try/catch handling still exists in Connect/Express. The way to solve it is to add your own try/catch block in the "root" which you can then use to emit an "error" event to the domain before connect sends the error response.
try {
// .. code here ..
} catch (err) {
domain.emit('error', err);
}
Another way to get around it is to just disconnect from the handler, like wrapping your code in a setImmediate block
Connect-domain allows you to catch all errors for connect modules including express.
Connect-domain https://github.com/baryshev/connect-domain
The example for express3: http://masashi-k.blogspot.com/2012/12/express3-global-error-handling-domain.html
The problem is that the exception happens during Connect's routing, which has both a try/catch
block around its execution, as well as a default error handler which prints out stack trace details when running in a non-production mode. Since the exception is handled inside of Express, it never reaches your outer layer for the domains to handle.
How it differs from exception2
is that the handler function for the '/'
route is executed directly by that Connect block, in the same stack as the original call that went through Express. The second exception occurs in a callback, after some I/O operation has returned, and therefore is executed by a stack originating from Node's event loop I/O handler, and so the try/catch
of Express isn't available to snag that exception and save the app server. In fact, if you comment out all the domain stuff, and trip exception2
it crashes Node.
Since only unhandled exceptions are routed to the domain mechanism, and since exception1
has a try/catch
visible in it's call stack above it, the exception is handled, and not forwarded to the domain.