Python sentry_sdk.capture_exception() Examples

The following are 17 code examples of sentry_sdk.capture_exception(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sentry_sdk , or try the search function .
Example #1
Source File: utils.py    From micromasters with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def custom_exception_handler(exc, context):
    """
    Custom exception handler for rest api views
    """
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    log.exception("An exception was intercepted by custom_exception_handler")
    response = exception_handler(exc, context)

    # if it is handled, just return the response
    if response is not None:
        return response

    # Otherwise format the exception only in specific cases
    if isinstance(exc, ImproperlyConfigured):
        # send the exception to Sentry anyway
        client.capture_exception()

        formatted_exception_string = "{0}: {1}".format(type(exc).__name__, str(exc))
        return Response(
            status=status.HTTP_500_INTERNAL_SERVER_ERROR,
            data=[formatted_exception_string]
        )
    return None 
Example #2
Source File: pusher.py    From SempoBlockchain with GNU General Public License v3.0 7 votes vote down vote up
def push_admin_credit_transfer(transfers):
    # If we only get one transfer, make it a list
    if not isinstance(transfers, list):
        transfers = [transfers]

    # Build prepared list of transfers we want to send
    pusher_batch_payload = []
    for transfer in transfers:
        for org in transfer.organisations:
            pusher_transfer_payload = {}
            pusher_transfer_payload['data'] = {}
            pusher_transfer_payload['data']['credit_transfer'] = credit_transfer_schema.dump(transfer).data
            pusher_transfer_payload['name'] = 'credit_transfer'
            pusher_transfer_payload['channel'] = current_app.config['PUSHER_ENV_CHANNEL'] + '-' + str(org.id)
            pusher_batch_payload.append(pusher_transfer_payload)

    # Break the list of prepared transfers into MAX_BATCH_SIZE chunks and send each batch to the API
    for pusher_payload_chunk in misc.chunk_list(pusher_batch_payload, PUSHER_MAX_BATCH_SIZE):
        try:
            async_pusher_trigger_batch.submit(pusher_payload_chunk)
        except Exception as e:
            print(e)
            sentry_sdk.capture_exception(e) 
Example #3
Source File: errorpages.py    From zing with GNU General Public License v3.0 7 votes vote down vote up
def log_exception(request, exception, tb):
    if sentry_sdk is not None:
        sentry_sdk.capture_exception(exception)
        return

    # Send email to admins with details about exception
    ip_type = (
        request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS
        and "internal"
        or "EXTERNAL"
    )
    msg_args = {
        "ip_type": ip_type,
        "path": request.path,
    }
    subject = "Error (%(ip_type)s IP): %(path)s" % msg_args

    try:
        request_repr = repr(request)
    except:
        request_repr = "Request repr() unavailable"

    msg_args = (str(exception.args[0]), tb, request_repr)
    message = "%s\n\n%s\n\n%s" % msg_args
    mail_admins(subject, message, fail_silently=True) 
Example #4
Source File: test_falcon.py    From sentry-python with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def test_500(sentry_init, capture_events):
    sentry_init(integrations=[FalconIntegration()])

    app = falcon.API()

    class Resource:
        def on_get(self, req, resp):
            1 / 0

    app.add_route("/", Resource())

    def http500_handler(ex, req, resp, params):
        sentry_sdk.capture_exception(ex)
        resp.media = {"message": "Sentry error: %s" % sentry_sdk.last_event_id()}

    app.add_error_handler(Exception, http500_handler)

    events = capture_events()

    client = falcon.testing.TestClient(app)
    response = client.simulate_get("/")

    (event,) = events
    assert response.json == {"message": "Sentry error: %s" % event["event_id"]} 
Example #5
Source File: dbot.py    From avrae with GNU General Public License v3.0 7 votes vote down vote up
def log_exception(exception=None, context: commands.Context = None):
        if config.SENTRY_DSN is None:
            return

        with sentry_sdk.push_scope() as scope:
            if context:
                # noinspection PyDunderSlots,PyUnresolvedReferences
                # for some reason pycharm doesn't pick up the attribute setter here
                scope.user = {"id": context.author.id, "username": str(context.author)}
                scope.set_tag("message.content", context.message.content)
                scope.set_tag("is_private_message", context.guild is None)
                scope.set_tag("channel.id", context.channel.id)
                scope.set_tag("channel.name", str(context.channel))
                if context.guild is not None:
                    scope.set_tag("guild.id", context.guild.id)
                    scope.set_tag("guild.name", str(context.guild))
            sentry_sdk.capture_exception(exception) 
Example #6
Source File: test_aws.py    From sentry-python with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def test_initialization_order(run_lambda_function):
    """Zappa lazily imports our code, so by the time we monkeypatch the handler
    as seen by AWS already runs. At this point at least draining the queue
    should work."""

    events, _response = run_lambda_function(
        LAMBDA_PRELUDE
        + dedent(
            """
            def test_handler(event, context):
                init_sdk()
                sentry_sdk.capture_exception(Exception("something went wrong"))
        """
        ),
        b'{"foo": "bar"}',
    )

    (event,) = events
    assert event["level"] == "error"
    (exception,) = event["exception"]["values"]
    assert exception["type"] == "Exception"
    assert exception["value"] == "something went wrong" 
Example #7
Source File: exception_handler.py    From renku-python with Apache License 2.0 7 votes vote down vote up
def _handle_sentry(self):
        """Handle exceptions using Sentry."""
        from sentry_sdk import capture_exception, configure_scope
        from sentry_sdk.utils import capture_internal_exceptions

        with configure_scope() as scope:
            with capture_internal_exceptions():
                from git import Repo
                from renku.core.commands import get_git_home
                from renku.core.models.provenance.agents import Person

                repo = Repo(get_git_home())
                user = Person.from_git(repo)

                scope.user = {'name': user.name, 'email': user.email}

            event_id = capture_exception()
            click.echo(
                _BUG + 'Recorded in Sentry with ID: {0}\n'.format(event_id),
                err=True,
            )
            raise 
Example #8
Source File: test_modules.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_basic(sentry_init, capture_events):
    sentry_init(integrations=[ModulesIntegration()])
    events = capture_events()

    sentry_sdk.capture_exception(ValueError())

    (event,) = events
    assert "sentry-sdk" in event["modules"]
    assert "pytest" in event["modules"] 
Example #9
Source File: service.py    From raiden-services with MIT License 6 votes vote down vote up
def handle_event(event: Event, context: Context) -> None:
    """ Calls the handler for the given event.

    Exceptions are caught and generate both error logs and sentry issues.
    Events are not retried after an exception.
    """
    log.debug(
        "Processing event",
        event_=event,
        latest_confirmed_block=context.latest_confirmed_block,
        latest_unconfirmed_block=context.get_latest_unconfirmed_block(),
    )
    handler = HANDLERS.get(type(event))

    if handler:
        with sentry_sdk.push_scope() as sentry_scope:
            sentry_scope.set_tag("event", event.__class__.__name__)
            try:
                handler(event, context)
                log.debug(
                    "Processed event",
                    num_scheduled_events=context.database.scheduled_event_count(),
                )
            except Exception as ex:  # pylint: disable=broad-except
                log.error("Error during event handler", handled_event=event, exc_info=ex)
                sentry_sdk.capture_exception(ex) 
Example #10
Source File: sentry.py    From review with Mozilla Public License 2.0 6 votes vote down vote up
def report_to_sentry(e):
    sentry_sdk.capture_exception(e) 
Example #11
Source File: sentry_integration.py    From packit-service with MIT License 6 votes vote down vote up
def send_to_sentry(ex):
    # so that we don't have to have sentry sdk installed locally
    import sentry_sdk

    sentry_sdk.capture_exception(ex) 
Example #12
Source File: sentry.py    From fbs with GNU General Public License v3.0 6 votes vote down vote up
def handle(self, exc_type, exc_value, enriched_tb):
        if self._rate_limiter.please():
            sentry_sdk.capture_exception((exc_type, exc_value, enriched_tb)) 
Example #13
Source File: ip_address.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def ip(self, ip):

        self._ip = ip

        if ip is not None:

            try:
                mt.set_ip_location(self.id, ip)
            except Exception as e:
                print(e)
                sentry_sdk.capture_exception(e)
                pass 
Example #14
Source File: blockchain_transaction.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def get_usd_to_satoshi_rate():

    blockchain_task = celery_app.signature('worker.celery_tasks.get_usd_to_satoshi_rate')
    # TODO: Convert to task_runner
    result = blockchain_task.apply_async()

    try:
        conversion_rate = result.wait(timeout=3, propagate=True, interval=0.5)

    except Exception as e:
        print(e)
        sentry_sdk.capture_exception(e)
        raise BlockchainError("Blockchain Error")

    finally:
        result.forget()

    return conversion_rate 
Example #15
Source File: pusher.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def push_user_transfer_confirmation(receive_user, transfer_random_key):
    try:
        async_pusher_trigger.submit(
            'private-user-{}-{}'.format(current_app.config['DEPLOYMENT_NAME'], receive_user.id),
            'payment_confirmed',
            {'transfer_random_key': transfer_random_key}
        )
    except Exception as e:
        print(e)
        sentry_sdk.capture_exception(e) 
Example #16
Source File: user.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def save_photo_and_check_for_duplicate(url, new_filename, image_id):
    save_to_s3_from_url(url, new_filename)

    try:
        rekognition_task = celery_app.signature('worker.celery_tasks.check_for_duplicate_person',
                                                args=(new_filename, image_id))
        # TODO: Standardize this task (pipe through execute_synchronous_celery)
        rekognition_task.delay()
    except Exception as e:
        print(e)
        sentry_sdk.capture_exception(e)
        pass 
Example #17
Source File: kyc_application_api.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def handle_kyc_documents(data=None,document_country=None,document_type=None,kyc_details=None):
    for (key, value) in data.items():
        if set([key]).intersection(set(['document_front_base64', 'document_back_base64', 'selfie_base64'])) and value is not None:
            try:
                new_filename = generate_new_filename(original_filename="{}-{}.jpg".format(key, document_country), file_type='jpg')
                save_to_s3_from_image_base64(image_base64=value, new_filename=new_filename)
                uploaded_document = UploadedResource(filename=new_filename, reference=document_type,
                                                     user_filename=key)
                db.session.add(uploaded_document)
                # tie document to kyc application
                uploaded_document.kyc_application_id = kyc_details.id
            except Exception as e:
                print(e)
                sentry_sdk.capture_exception(e)
                pass