Beispiel #1
0
    def test_does_exclude_filtered_types(self, exc_info, mock_capture):
        exc_info.return_value = self.exc_info
        get_client().ignore_exceptions = set(['ValueError'])

        sentry_exception_handler(request=self.request)

        assert not mock_capture.called
Beispiel #2
0
    def test_does_exclude_filtered_types(self, get_option, exc_info, captureException):
        exc_info.return_value = self.exc_info
        get_option.return_value = ['ValueError']

        sentry_exception_handler(request=self.request)

        assert not captureException.called
Beispiel #3
0
    def test_does_exclude_filtered_types(self, get_option, exc_info, captureException):
        exc_info.return_value = self.exc_info
        get_option.return_value = ['ValueError']

        sentry_exception_handler(request=self.request)

        assert not captureException.called
Beispiel #4
0
def error_code_exception_handler(exc, context):
    if isinstance(exc, ErrorCode):
        return r(exc.code, err_msg=exc.err_msg)
    elif isinstance(exc, (NotAuthenticated, AuthenticationFailed)):
        print(exc)
        return r('USER_NOT_LOGGED_IN')
    elif isinstance(exc, MethodNotAllowed):
        return r('METHOD_NOT_ALLOWED')
    elif isinstance(exc, PermissionDenied):
        user = context['request'].user
        if re.match("CSRF Failed: ", exc.detail):
            return r('CSRF_FAILED')
        if isinstance(user, UserProfile) and user.is_banned:
            return r('USER_BANNED')
        else:
            return r('PERMISSION_DENIED')
    elif isinstance(exc, Ratelimited):
        return r('RATE_LIMITED')

    response = exception_handler(exc, context)
    if response is None:
        logger.exception(exc)
        sentry_exception_handler(request=context)
        return r('INTERNAL_ERROR')
    else:
        return response
Beispiel #5
0
 async def handle(self, body):
     try:
         await self.check_permission()
         await self.handle_request(body)
     except Exception:
         logger.error(traceback.format_exc())
         sentry_exception_handler()
         await self.send_json_response('INTERNAL_ERROR')
Beispiel #6
0
    def process_exception(self, request, exception):
        msg = force_unicode(exception)
        if isinstance(exception, Http404):
            if request.is_ajax():
                return self._ajax_error(404, msg)
        elif isinstance(exception, PermissionDenied):
            if request.is_ajax():
                return self._ajax_error(403, msg)

            templatevars = {}
            templatevars["permission_error"] = msg

            if not request.user.is_authenticated():
                login_msg = _(
                    'You need to <a href="%(login_link)s">login</a> ' "to access this page.",
                    {"login_link": "%s%s" % (l("/accounts/login/"), get_next(request))},
                )
                templatevars["login_message"] = login_msg

            return HttpResponseForbidden(render_to_string("403.html", templatevars, RequestContext(request)))
        else:
            # FIXME: implement better 500
            tb = traceback.format_exc()
            print >>sys.stderr, tb

            if not settings.DEBUG:
                try:
                    templatevars = {}
                    templatevars["exception"] = msg
                    if hasattr(exception, "filename"):
                        msg = _(
                            "Error accessing %(filename)s, Filesystem " "sent error: %(errormsg)s",
                            {"filename": exception.filename, "errormsg": exception.strerror},
                        )
                        templatevars["fserror"] = msg

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

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

                        message = "%s\n\n%s\n\n%s" % (unicode(exception.args[0]), tb, request_repr)
                        mail_admins(subject, message, fail_silently=True)
                    else:
                        sentry_exception_handler(request=request)

                    if request.is_ajax():
                        return self._ajax_error(500, msg)

                    return HttpResponseServerError(render_to_string("500.html", templatevars, RequestContext(request)))
                except:
                    # Let's not confuse things by throwing an exception here
                    pass
Beispiel #7
0
 def process_exception(self, request, exception):
     if not settings.DEBUG:
         sentry_exception_handler(request=request)
         if request.path != alipay_wap_sync_back:
             return TemplateResponse(request, "500.html", {'exception': exception})
         else:
             return HttpResponseRedirect("%s?message=%s" % (reverse_lazy('error'), exception.message))
     else:
         return None
Beispiel #8
0
    def test_ignore_exceptions_with_module_match(self, get_option, exc_info, captureException):
        exc_info.return_value = self.exc_info
        get_option.return_value = ['builtins.ValueError']
        if not six.PY3:
            get_option.return_value = ['exceptions.ValueError']

        sentry_exception_handler(request=self.request)

        assert not captureException.called
Beispiel #9
0
    def test_ignore_exceptions_with_expression_match(self, get_option, exc_info, captureException):
        exc_info.return_value = self.exc_info
        get_option.return_value = ["builtins.*"]
        if not six.PY3:
            get_option.return_value = ["exceptions.*"]

        sentry_exception_handler(request=self.request)

        assert not captureException.called
Beispiel #10
0
    def test_ignore_exceptions_with_module_match(self, get_option, exc_info, captureException):
        exc_info.return_value = self.exc_info
        get_option.return_value = ['builtins.ValueError']
        if not six.PY3:
            get_option.return_value = ['exceptions.ValueError']

        sentry_exception_handler(request=self.request)

        assert not captureException.called
Beispiel #11
0
def _send_mail(subject, context, template, user=None, email=None, name=None, reason=None, from_email=None, dialog=None):
    log = None

    if user is not None:
        if email is None and hasattr(user, "email"):
            email = user.email
        if name is None and hasattr(user, "get_full_name"):
            name = unicode(user.get_full_name()).encode("utf-8")
    elif email is None:
        return
    else:
        if name is None:
            name = ""
    if isinstance(context, dict):
        context = Context(context)
    if not isinstance(template, Template):
        template = get_template(template)

    subject_t = Template(subject)
    mail = Mail(reason=reason, subject=subject, dialog=dialog)
    if log:
        mail.campaign = log.campaign
    mail.save()
    context.update(
        {
            "MAIN_DOMAIN": "lasercorp.ru",
            "MEDIA_DOMAIN": "127.0.0.1",
            "STATIC_URL": settings.STATIC_URL,
            "user": user,
            "user_email": email.replace("\n", ""),
            "user_name": name,
            "email_hash": email.encode("base64"),
            "mail_obj": mail,
        }
    )
    msg_text = template.render(context)

    headers = None
    if reason:
        if reason < 0:
            id_str = "sys{0}".format(abs(reason))
        else:
            id_str = "cam{0}".format(reason)
        headers = {"List-id": id_str, "X-Mailru-Msgtype": id_str}
    msg = EmailMessage(subject_t.render(context), msg_text, from_email, [email], headers=headers)
    msg.content_subtype = "html"
    try:
        msg.send()
        if log:
            log.count_sent += 1
            # email_service(log, email)
    except Exception:
        sentry_exception_handler()
        mail.save()
        if log:
            log.count_fail += 1
Beispiel #12
0
    def test_does_exclude_filtered_types(self, exc_info, mock_capture):
        exc_info.return_value = self.exc_info
        try:
            get_client().ignore_exceptions = set(['ValueError'])

            sentry_exception_handler(request=self.request)
        finally:
            get_client().ignore_exceptions.clear()

        assert not mock_capture.called
Beispiel #13
0
    def test_ignore_exceptions_with_module_match(self, exc_info, mock_capture):
        exc_info.return_value = self.exc_info

        if six.PY3:
            get_client().ignore_exceptions = set(['builtins.ValueError'])
        else:
            get_client().ignore_exceptions = set(['exceptions.ValueError'])

        sentry_exception_handler(request=self.request)

        assert not mock_capture.called
Beispiel #14
0
    def test_ignore_exceptions_with_expression_match(self, exc_info, mock_capture):
        exc_info.return_value = self.exc_info

        try:
            if six.PY3:
                get_client().ignore_exceptions = set(['builtins.*'])
            else:
                get_client().ignore_exceptions = set(['exceptions.*'])
            sentry_exception_handler(request=self.request)
        finally:
            get_client().ignore_exceptions.clear()

        assert not mock_capture.called
Beispiel #15
0
    def test_ignore_exceptions_with_module_match(self, exc_info, mock_capture):
        exc_info.return_value = self.exc_info

        try:
            if six.PY3:
                get_client().ignore_exceptions = set(['builtins.ValueError'])
            else:
                get_client().ignore_exceptions = set(['exceptions.ValueError'])
            sentry_exception_handler(request=self.request)
        finally:
            get_client().ignore_exceptions.clear()

        assert not mock_capture.called
Beispiel #16
0
def handler500(request):
    """
    An error handler which exposes the request object to the error template.
    """
    from django.template import Context, loader
    from django.http import HttpResponseServerError
    from raven.contrib.django.models import sentry_exception_handler

    import logging
    import sys

    sentry_exception_handler(request=request)
    context = { 'request': request }

    t = loader.get_template('500.html') # You need to create a 500.html template.
    return HttpResponseServerError(t.render(Context(context)))
Beispiel #17
0
def handler500(request):
    """
    An error handler which exposes the request object to the error template.
    """
    from django.template import Context, loader
    from django.http import HttpResponseServerError
    from raven.contrib.django.models import sentry_exception_handler

    import logging
    import sys

    sentry_exception_handler(request=request)
    context = {'request': request}

    t = loader.get_template(
        '500.html')  # You need to create a 500.html template.
    return HttpResponseServerError(t.render(Context(context)))
Beispiel #18
0
def log_exception(request, exception, tb):
    if sentry_exception_handler is None:
        # 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 = (unicode(exception.args[0]), tb, request_repr)
        message = "%s\n\n%s\n\n%s" % msg_args
        mail_admins(subject, message, fail_silently=True)
    else:
        sentry_exception_handler(request=request)
Beispiel #19
0
def log_exception(request, exception, tb):
    if sentry_exception_handler is None:
        # 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 = (unicode(exception.args[0]), tb,
                    request_repr)
        message = "%s\n\n%s\n\n%s" % msg_args
        mail_admins(subject, message, fail_silently=True)
    else:
        sentry_exception_handler(request=request)
Beispiel #20
0
    def test_does_capture_exception(self, exc_info, captureException):
        exc_info.return_value = self.exc_info
        sentry_exception_handler(request=self.request)

        captureException.assert_called_once_with(exc_info=self.exc_info,
                                                 request=self.request)
Beispiel #21
0
    def test_does_capture_exception(self, exc_info, captureException):
        exc_info.return_value = self.exc_info
        sentry_exception_handler(request=self.request)

        captureException.assert_called_once_with(exc_info=self.exc_info, request=self.request)
Beispiel #22
0
    def process_exception(self, request, exception):
        msg = unicode(str(exception), 'utf-8')
        if isinstance(exception, Http404):
            if request.is_ajax():
                return self._ajax_error(404, msg)
        elif isinstance(exception, PermissionDenied):
            if request.is_ajax():
                return self._ajax_error(403, msg)

            templatevars = {}
            templatevars['permission_error'] = msg

            if not request.user.is_authenticated():
                login_msg = _('You need to <a href="%(login_link)s">login</a> '
                              'to access this page.',
                              {'login_link': "%s%s" % \
                                (l("/accounts/login/"), get_next(request))})
                templatevars["login_message"] = login_msg

            return HttpResponseForbidden(
                render_to_string('403.html', templatevars,
                                 RequestContext(request)))
        else:
            #FIXME: implement better 500
            tb = traceback.format_exc()
            print >> sys.stderr, tb

            if not settings.DEBUG:
                try:
                    templatevars = {}
                    templatevars['exception'] = msg
                    if hasattr(exception, 'filename'):
                        msg = _(
                            'Error accessing %(filename)s, Filesystem '
                            'sent error: %(errormsg)s', {
                                'filename': exception.filename,
                                'errormsg': exception.strerror
                            })
                        templatevars['fserror'] = msg

                    if sentry_exception_handler is None:
                        # Send email to admins with details about exception
                        ip_type = (request.META.get('REMOTE_ADDR') in \
                                settings.INTERNAL_IPS and 'internal' or 'EXTERNAL')
                        subject = 'Error (%s IP): %s' % (ip_type, request.path)

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

                        message = "%s\n\n%s\n\n%s" % (unicode(
                            exception.args[0]), tb, request_repr)
                        mail_admins(subject, message, fail_silently=True)
                    else:
                        sentry_exception_handler(request=request)

                    if request.is_ajax():
                        return self._ajax_error(500, msg)

                    return HttpResponseServerError(
                        render_to_string('500.html', templatevars,
                                         RequestContext(request)))
                except:
                    # Let's not confuse things by throwing an exception here
                    pass
Beispiel #23
0
    def process_exception(self, request, exception):
        msg = force_unicode(exception)
        if isinstance(exception, Http404):
            if request.is_ajax():
                return self._ajax_error(404, msg)
        elif isinstance(exception, Http400):
            if request.is_ajax():
                return self._ajax_error(400, msg)
        elif isinstance(exception, PermissionDenied):
            if request.is_ajax():
                return self._ajax_error(403, msg)

            templatevars = {
                'permission_error': msg,
            }

            if not request.user.is_authenticated():
                msg_args = {
                    'login_link':
                    "%s%s" %
                    (reverse('pootle-profile-login'), get_next(request)),
                }
                login_msg = _(
                    'You need to <a href="%(login_link)s">login</a> '
                    'to access this page.', msg_args)
                templatevars["login_message"] = login_msg

            return HttpResponseForbidden(
                render_to_string('errors/403.html', templatevars,
                                 RequestContext(request)))
        elif (exception.__class__.__name__
              in ('OperationalError', 'ProgrammingError', 'DatabaseError')):
            # HACKISH: Since exceptions thrown by different databases do
            # not share the same class heirarchy (DBAPI2 sucks) we have to
            # check the class name instead. Since python uses duck typing
            # I will call this
            # poking-the-duck-until-it-quacks-like-a-duck-test

            if request.is_ajax():
                return self._ajax_error(500, msg)

            return HttpResponseServerError(
                render_to_string('errors/db.html', {'exception': msg},
                                 RequestContext(request)))

        else:
            #FIXME: implement better 500
            tb = traceback.format_exc()
            print >> sys.stderr, tb

            if not settings.DEBUG:
                try:
                    templatevars = {
                        'exception': msg,
                    }
                    if hasattr(exception, 'filename'):
                        msg_args = {
                            'filename': exception.filename,
                            'errormsg': exception.strerror,
                        }
                        msg = _(
                            'Error accessing %(filename)s, Filesystem '
                            'sent error: %(errormsg)s', msg_args)
                        templatevars['fserror'] = msg

                    if sentry_exception_handler is None:
                        # 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 = (unicode(exception.args[0]), tb,
                                    request_repr)
                        message = "%s\n\n%s\n\n%s" % msg_args
                        mail_admins(subject, message, fail_silently=True)
                    else:
                        sentry_exception_handler(request=request)

                    if request.is_ajax():
                        return self._ajax_error(500, msg)

                    return HttpResponseServerError(
                        render_to_string('errors/500.html', templatevars,
                                         RequestContext(request)))
                except:
                    # Let's not confuse things by throwing an exception here
                    pass
Beispiel #24
0
    def process_exception(self, request, exception):
        msg = force_unicode(exception)
        if isinstance(exception, Http404):
            if request.is_ajax():
                return self._ajax_error(404, msg)
        elif isinstance(exception, Http400):
            if request.is_ajax():
                return self._ajax_error(400, msg)
        elif isinstance(exception, PermissionDenied):
            if request.is_ajax():
                return self._ajax_error(403, msg)

            templatevars = {
                'permission_error': msg,
            }

            if not request.user.is_authenticated():
                msg_args = {
                    'login_link': "%s%s" % (l("/accounts/login/"),
                                            get_next(request)),
                }
                login_msg = _('You need to <a href="%(login_link)s">login</a> '
                              'to access this page.', msg_args)
                templatevars["login_message"] = login_msg

            return HttpResponseForbidden(
                    render_to_string('403.html', templatevars,
                                     RequestContext(request))
                )
        elif (exception.__class__.__name__ in
                ('OperationalError', 'ProgrammingError', 'DatabaseError')):
            # HACKISH: Since exceptions thrown by different databases do
            # not share the same class heirarchy (DBAPI2 sucks) we have to
            # check the class name instead. Since python uses duck typing
            # I will call this
            # poking-the-duck-until-it-quacks-like-a-duck-test
            return HttpResponseServerError(
                    render_to_string('db_error.html', {'exception': msg},
                                     RequestContext(request))
                )

        else:
            #FIXME: implement better 500
            tb = traceback.format_exc()
            print >> sys.stderr, tb

            if not settings.DEBUG:
                try:
                    templatevars = {
                        'exception': msg,
                    }
                    if hasattr(exception, 'filename'):
                        msg_args = {
                            'filename': exception.filename,
                            'errormsg': exception.strerror,
                        }
                        msg = _('Error accessing %(filename)s, Filesystem '
                                'sent error: %(errormsg)s', msg_args)
                        templatevars['fserror'] = msg

                    if sentry_exception_handler is None:
                        # 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 = (unicode(exception.args[0]), tb,
                                    request_repr)
                        message = "%s\n\n%s\n\n%s" % msg_args
                        mail_admins(subject, message, fail_silently=True)
                    else:
                        sentry_exception_handler(request=request)

                    if request.is_ajax():
                        return self._ajax_error(500, msg)

                    return HttpResponseServerError(
                        render_to_string('500.html', templatevars,
                                         RequestContext(request)))
                except:
                    # Let's not confuse things by throwing an exception here
                    pass