[Fixed]-How to ignore certain Python errors from Sentry capture

27👍

It took me some source-diving to actually find it, but the option in the new SDK is "ignore_errors". It takes an iterable where each element can be either a string or a type (like the old interface).

I hesitate to link to it because its an internal method that could change at any time, but here
is the snapshot of it at the time of me writing this.

As an example (reimplementing Markus’s answer):

import sentry_sdk

sentry_sdk.init(ignore_errors=[IgnoredErrorFoo, IgnoredErrorBar])

16👍

You can use before-send to filter errors by arbitrary criteria. Since it’s unclear what you actually want to filter by, here’s an example that filters by type. However, you can extend it with custom logic to e.g. match by exception message.

import sentry_sdk

def before_send(event, hint):
    if 'exc_info' in hint:
        exc_type, exc_value, tb = hint['exc_info']
        if isinstance(exc_value, (IgnoredErrorFoo, IgnoredErrorBar)):
            return None
    return event

sentry_sdk.init(before_send=before_send)

4👍

To ignore all related errors, there are two ways:

  1. Use before_send
import sentry_sdk
from rest_framework.exceptions import ValidationError

def before_send(event, hint):
    if 'exc_info' in hint:
        exc_type, exc_value, tb = hint['exc_info'] 
        if isinstance(exc_value, (KeyError, ValidationError)):
            return None
    return event

sentry_sdk.init(
    dsn='SENTRY_DSN',
    before_send=before_send
)
  1. Use ignore_errors
import sentry_sdk
from rest_framework.exceptions import ValidationError

sentry_dsk.init(
    dsn='SENTRY_DSN',
    ignore_errors=[
       KeyError() ,
       ValidationError('my error message'),
    ]  # All event error (KeyError, ValidationError) will be ignored
)

To ignore a specific event error, just ignore this event ValidationError('my error message') with a custom def before_send:

def before_send(event, hint):
    if 'exc_info' in hint:
        exc_type, exc_value, tb = hint['exc_info'] 
        if exc_value.args[0] in ['my error message', 'my error message 2', ...]:
            return None
    return event

This is documented in the sentry-python documentation at: https://docs.sentry.io/platforms/python/guides/django/configuration/filtering/

Note: The hint parameter has 3 cases, you need to know in which case your error will be.
https://docs.sentry.io/platforms/python/guides/django/configuration/filtering/hints/

Leave a comment