Sentry with User Context for Express

Today I tried to add some user context to's issue tracking. This is helpful since it allows you to track which users get what errors.

Klart's backend is based on Node and Express so naturally this will target those technologies. My first atempt was to use the default Raven.errorHandler(). However, it was a little bit tricky to wrap it in a Raven context. Having a look at the source code revealed a few things though. The Express middleware is basically just some logic on top of the default Node Raven.captureException(e). So I decided to make my own handler with context. This is what it looks like:

function ravenErrorHandlerWithContext(err, req, res, next) {
  return Raven.context(() => {
    const status =
      err.status ||
      err.statusCode ||
      err.status_code ||
      (err.output && err.output.statusCode) ||
    if (status < 500) return next(err);
    if (req.user) {
      Raven.setContext({ user: { id: req.user._id } });
    const eventId = Raven.captureException(err, { req });
    res.sentry = eventId;
    return next(err);

What it does is basically just wrapping the error handling stuff in a Raven context which contains some info about the logged in user (if any). However, if the error is not of the 500 kind, we simply continue to the next handler ☕️.