[Fixed]-How do you raise a python exception and include additional data for Sentry?


I log exceptions using the logging library so after debugging the code a bit, I noticed the extra parameter:

import logging
logger = logging.getLogger('my_app_name')

def do_something():

        #do some stuff here that might break

    except Exception, e:
        logger.error(e, exc_info=1, extra={'extra-data': 'blah', })

Passing exc_info=1 is the same as calling logger.exception. However, exception() does not accept kwargs, which are required for using the extra parameter.

These values will show up in the ‘Additional Data’ section of the Sentry Error dashboard.



wes’ answer didn’t help me because I want to actually raise an exception, not only log it.

Here’s what I did (client is the Raven Sentry client):

client.extra_context({'foo': 'bar'})
raise RuntimeError('Whoops, something went wrong!')


You might try one of these two approaches:

>>> # Raise the exception with the data you want.
>>> raise Exception('extra information')
Traceback (most recent call last):
  File "<pyshell#64>", line 1, in <module>
    raise Exception('extra information')
Exception: extra information
>>> # Catch an exception and add extra arguments.
>>> try:
    raise Exception()
except Exception as error:
    error.args += ('extra information',)

Traceback (most recent call last):
  File "<pyshell#68>", line 2, in <module>
    raise Exception()
Exception: extra information

You can add as many additional data fields as you want by adding more arguments.


The Sentry handler adds that info in your screenshot when capturing the message for an exception, and takes that information from the traceback, not the exception itself.

You can add extra fields by passing extra keyword arguments to .capture(); the Django client does so for you if you pass in the request object, for example.

Currently, no other data is taken from exceptions. You’d have to expand the exception handling yourself to add such a facility.


None of the existing answers served my exact use case well (which was to add additional context from the django Request object into the sentry data). What ended up working very well for that after some digging was overriding the client using the SENTRY_CLIENT setting.

Here’s a complete simple use case:

from raven.contrib.django.raven_compat import DjangoClient

class CustomSentryClient(DjangoClient):

    def get_data_from_request(self, request):
        result = super(EToolsSentryClient, self).get_data_from_request(request)
        if getattr(request, 'custom_field', None):
            if 'extra' not in result:
                result['extra'] = {}
            result['extra']['custom_field'] = request.custom_field
        return result

and then in settings.py you would just add

SENTRY_CLIENT = 'myapp.CustomSentryClient'

Leave a comment