sentry-javascript: Pass req in Sentry.captureException

It looks like Raven was able to take context information including a req parameter, but Sentry isn’t allowing me to to do this. So something like this:

Sentry.captureException(Error("An error"), {
  user: { id: 123 },
  req: req, // Request object from HTTP web server
  tags: { component: 'main', method: 'doSomething' },
  extra: { catType: cat.type },
  level: 'error'
})

Is this still possible with Sentry? If not, how can I achieve the same thing (especially sending the req)?

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 17 (9 by maintainers)

Most upvoted comments

@HazAT Thanks, it’s works.

My solutions for Restify 4.x:

const server = restify.createServer({
  handleUncaughtExceptions: true,
})

const onError = (req, res, route, error) => {
  Sentry.withScope(scope => {
    // scope.setTag()
    // scope.setUser()

    scope.addEventProcessor(async event => {
      return Sentry.Handlers.parseRequest(event, req)
    })

    Sentry.captureException(error)
  })
}

server.app.on('uncaughtException', (req, res, route, error) => {
  onError(req, res, route, error)
  res.send(new restify.errors.InternalServerError(error))
})

// Loggin RestError/NotFound/etc
// server.app.on('after', onError)

@vhu I guess our docs can be improved here: https://docs.sentry.io/platforms/node/koa/

But you would do something in the lines of in your custom scope.addEventProcessor do:

Sentry.Handlers.parseRequest(event, req);

If that solves it we can add it to the docs.

I can absolutely second that updating the Koa documentation with that snippet would be a huge help. Took me quite a bit of time to figure out why my captured exceptions were missing the request meta data.

Right now it only advocates:

app.on('error', err => {
  Sentry.captureException(err);
});

but changing that to:

app.on('error', (err, ctx) => {
  Sentry.withScope((scope) => {
    scope.addEventProcessor(async (event) => Sentry.Handlers.parseRequest(event, ctx.request));
    Sentry.captureException(err);
  });
});

would be a huge improvement and ensure people get all the request info attached to their requests.

We dropped the second “magic” arbitrary object in captureException the new official way of doing this is setting stuff on the scope like:

Sentry.withScope(scope => {
    scope.setExtra('debug', false);
    // scope.setTag
    // scope.setUser
    // scope.setLevel
    Sentry.captureException(e);
});

Sending the req or something else, either requires to add it in the beforeSend option. Or add a custom eventProcessor to the scope:

Sentry.withScope(scope => {
    scope.addEventProcessor(event => {
      // change anything in the event here
    });
    Sentry.captureException(e);
});

Hope this helps.