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.

This documentation is for version 7 of the BugSnag JavaScript notifier. If you are using older versions, we recommend upgrading to the latest release using our Upgrade guide. Documentation for the previous release can be found on our legacy pages.

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 = Bugsnag.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 Bugsnag.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 = Bugsnag.getPlugin('contextualize')

API

contextualize(cb, onError)

Executes cb(). Any error that can be traced back to cb() will trigger the onError callback, the same as the onError parameter of notify(), which provides access to the event data.

Example

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