Node utilities

Handling asynchronous errors in Node.js can involve a lot of boilerplate. When running in Node.js the universal JS notifier provides some utilities to help reduce the amount of code you have to write in order to achieve decent error handling.

intercept(cb)

Many operations in Node.js are asynchronous.

When you write asynchronous code with Node-style error first callbacks, or using promises, you must handle every error otherwise they will be swallowed and you will never know about them.

Handling every error can be repetitive, so Bugsnag provides an intercept() function which will handle the error for you, and call your callback only if the operation was successful.

// intercept() is a plugin which is built in by default
// The way you access plugins is to retrieve them by name from the client…

var intercept = bugsnagClient.getPlugin('intercept')

API

intercept(optionalCb)

Returns a function which you can pass as a Node-style error first callback, or as a Promise catch clause. If you supply the optional cb, it will be called only if there was no error parameter with the error parameter removed from the arguments.

Examples

Without intercept()

fs.readFile('does_not_exist.txt', function (err, data) {
  if (err) {
    return bugsnagClient.notify(err)
  }
})

With intercept()

fs.readFile('does_not_exist.txt', intercept())

Providing an optional callback

fs.readFile('does_not_exist.txt', intercept(function (data) {
  // notice there is no `err` parameter in this callback. it
  // is only ever called when no err is present.
  console.log('success!')
}))

Using promises

var readFile = promisify(fs.readFile)
readFile
  .then(function (data) {
    console.log('success')
  })
  .catch(intercept()) // << doesn't need a callback because that goes in .then()

contextualize(cb)

When asynchronous errors happen in Node.js, it’s often hard to track them back to where they originated. This is because the stacktraces are not maintained in asynchronous execution.

To provide context around errors from a particular part of your application, you can use contextualize(cb) to attach info that might be useful later on. This info will be attached to any errors detected by Bugsnag which originated there.

var contextualize = bugsnagClient.getPlugin('contextualize')

API

contextualize(cb, opts)

Executes cb(). Any error that can be traced back to cb() will include the opts context in the Bugsnag error report.

opts is the same as the opts parameter of notify() which includes:

  • context
  • metaData
  • user
  • beforeSend
  • severity
  • device
  • request

Example

contextualize(function () {
  fs.createReadStream('does not exist')
}, {
  metaData: {
    component: { name: 'file reader' }
  },
  context: 'cmp/file_reader'
})