sentry-python icon indicating copy to clipboard operation
sentry-python copied to clipboard

ignore error post init

Open zhaowb opened this issue 3 years ago • 1 comments

Problem Statement

Our team is using aws lambda layer and cloudformation macro to automatically initialize sentry so we don't have to import and init sentry in every application code. But this brings a problem that if we want to ignore a custom error, we can find a standard way to do it.

A more generic requirement is, need a standard way to update existing client's options.

Solution Brainstorm

Our solution is this:

In our common util code:

try:
    import sentry_sdk
except:
    sentry_sdk = None

def sentry_ignore(*exceptions):
    """ignore list of errors
    :param exceptions: string full qualified name of error or ErrorClass
    eg
    `sentry_ignore(CustomException, ValueError, 'my.package.file.CustomException')`

    This can be called in module level because sentry lambda handler code calls `sentry_sdk.init()` in
    module level too. Because cloudformation macro transforms all lambda handlers to sentry layer handler,
    sentry_sdk.init() is always called before any application code.
    See sentry lambda hanlder used in layer in downloaded file, it's not in github repo.

    Command to download layer:
    ```bash
    aws lambda get-layer-version-by-arn --arn arn:aws:lambda:ap-southeast-2:943013980633:layer:SentryPythonServerlessSDK:22
    ```
    sentry_sdk.init() is called in integrations/init_serverless_sdk/__init__.py line 21.
    """
    if not sentry_sdk:
        # not running in lambda env
        # sentry_sdk is in lambda layer, not used in local, ie pytest
        return
    # see usage of 'Hub.current.*' in https://github.com/getsentry/sentry-python/blob/7417d9607eb87aa7308d8b3af5fb47ca51709105/sentry_sdk/api.py#L97
    # see how get client from hub in https://github.com/getsentry/sentry-python/blob/7417d9607eb87aa7308d8b3af5fb47ca51709105/sentry_sdk/hub.py#L317
    # see _Client.options init https://github.com/getsentry/sentry-python/blob/7417d9607eb87aa7308d8b3af5fb47ca51709105/sentry_sdk/client.py#L88
    # see options["ignore_errors"] in https://github.com/getsentry/sentry-python/blob/7417d9607eb87aa7308d8b3af5fb47ca51709105/sentry_sdk/client.py#L234
    from sentry_sdk.hub import Hub
    client, _ = Hub.current._stack[-1]
    for exc in exceptions:
        if not isinstance(exc, str):
            if issubclass(exc, Exception):
                exc = f'{exc.__module__}.{exc.__name__}'
            else:
                print('WARNING: sentry_ignore expects "module.exception_class_name" or ExceptionType,'
                      ' unknown arg {repr(exc)}')
                continue
        if exc not in client.options['ignore_errors']:
            client.options['ignore_errors'].append(exc)
            print(f'INFO: sentry_ignore ignore_errors.append {repr(exc)}')
        else:
            print(f'INFO: sentry_ignore ignore_errors duplicate {repr(exc)}')

Example to ignore a custom error in application code:

from utils import sentry_ignore  # 'utils' is our common package name

class CustomAbcError(Exception):
    pass

class CustomDefError(Exception):
    pass

sentry_ignore(CustomAbcError, CustomDefError)

zhaowb avatar Apr 26 '22 20:04 zhaowb

Hello @zhaowb

Thanks for bringing this up.

First: Your solution looks good! One thing about getting the client, in our integrations we do this like this (its a little easier to read):

hub = Hub.current
client = hub.client

Yes, interacting with the Sentry installation in the Lambda Layer is not perfect right now. The Lambda Layer is more for people that do not want to change the code to enable Sentry.

You could also skip the Lambda Layer and manually initialize Sentry (in your Lambda function, outside the handler function) like described here: https://docs.sentry.io/platforms/python/guides/aws-lambda/

If you (or anybode else reading this) have any ideas on how to make communication with the Sentry integration inside the Lambda Layer from the Lambda function we are happy to hear!

antonpirker avatar May 24 '22 07:05 antonpirker