Skip to content

Instantly share code, notes, and snippets.

@watson
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save watson/2ddc524392f3fd368ef7 to your computer and use it in GitHub Desktop.
Save watson/2ddc524392f3fd368ef7 to your computer and use it in GitHub Desktop.
Example using the async-state module
var http = require('http')
var asyncState = require('async-state')
process.on('uncaughtException', function (err) {
if (asyncState.req) {
console.log('An error occurred while processing request for', asyncState.req.url)
} else {
console.log('An error occurred outside of an HTTP request')
}
})
http.createServer(function (req, res) {
// when ever an HTTP request is received, we call an async function that
// takes a long time to finish. The async function unfortunately have a
// bug so that it thorws an Error after 10 seconds.
//
// Multiple HTTP requests can be active when the error occurrs, so we
// use asyncState to keep track of which HTTP request that fail.
asyncState.req = req
doWork(function () {
res.end()
})
}).listen(3000)
// async-state doesn't leak state between different async call stacks,
// so when doWork fails in 20 seconds it will not have access to any
// requests that might have arrived prior to the callback being called
setTimeout(doWork, 10000)
// Async function taking 10 seconds to finish
function doWork (cb) {
console.log('Preparing to do hard work...')
setTimeout(function () {
throw new Error('Bang!')
}, 10000)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment