wrap express request/response with node domains, inspired by and forked from express-domain-middleware
Hi! Are you using
process.uncaughtException in your express apps to keep them running?
OR...Do you just let your process crash on any unhandled exception and restart it?
Do you find it hard to pass "request.id" to 8 nested database calls so you can keep a context of what request you're working on?
How do you associate log entries with a specific request? Passing the request around everywhere again?
Domains can help.
First, read this
Second, realize once you enable domains
process.domain will give you the active domain.
Third, use this middleware to bind each request/response pair to its own domain.
var requestDomainWrapper = require'myhr-request-domain-wrapper-middleware';# before appuseapproutesappuserequestDomainWrapper;
Exports a function matching the signature of express middleware. Binds incoming request & response from express to a new domain. Assigns the domain a unique id.
If the domain emits an error event,
requestDomainWrapper will call
next(err) with the error event from the domain. This allows existing express specific error handling middleware to
function as if the error was hanlded by your application code. Allow me to demonstrate with an example:
///old-schoolappget'/error'dbquery'SELECT happiness()'iferr return nexterr;fsreadFile'alskdjflasd'iferr return nexterr;processnextTickthrow "congratulations, your node process crashed and the user request disconnected in a jarring way";;;;
now with less crashing...
//with request-domain-wrapper-middlewareappuserequire'myhr-request-domain-wrapper-middleware';appuseapprouter;appuseconsole.log'error on request %d %s %s: %j' processdomainid reqmethod requrl err;ressend500 "Something bad happened. :(";iferrdomain//you should think about gracefully stopping & respawning your server//since an unhandled error might put your application into an unknown state;appget'/error'dbquery'SELECT happiness()' processdomaininterceptfsreadFile'asldkfjasdf' processdomaininterceptprocessnextTickprocessdomaininterceptthrow "The individual request will be passed to the express error handler, and your application will keep running.";;;;;
I have to recommend using okay to gracefully fallback in the absence of domains. Plus..it's terse. Go, code golf!
var ok = require'okay';appuserequire'express-domain-middleware';appuseapprouter;appuseconsole.log'error on request %d %s %s: %j' processdomainid reqmethod requrl err;ressend500 "Something bad happened. :(";;appget'/error'dbquery'SELECT happiness()' oknextfsreadFile'asldkfjasdf' oknextprocessnextTickoknextthrow "The individual request will be passed to the express error handler, and your application will keep running.";;;;;