예제 #1
0
def custom_handler(exc, context):
    """
    Handle exceptions that are NOT `rest_framework.exceptions.APIException`-based exceptions
    """
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)
    request = context.get('request', None)
    view = context.get('view', None)

    if not response:

        q('CUSTOM EXCEPTION!', exc, request.data)

        # Get exception info
        exc_type, exc_value, exc_trace = sys.exc_info()

        q(exc_type, exc_value, exc_trace)

        # Customize exceptions that translate to HTTP-4XX status-codes
        if isinstance(exc, core_exceptions.ObjectDoesNotExist):
            msg = str(exc) # TODO! Translate this!
            data = {'detail': six.text_type(msg)}
            status_code = status.HTTP_404_NOT_FOUND

        elif isinstance(exc, AssertionError):
            if isinstance(exc.message, basestring):
              data = {'detail': six.text_type(exc.message)}
            else:
              data = exc.message
            status_code = status.HTTP_400_BAD_REQUEST

        else:
            q('UNHANDLED CUSTOM EXCEPTION!')

            # Unhandled exception; print and then just wrap to make render properly
            traceback.print_exception(exc_type, exc_value, exc_trace)
            try:
              msg = str(exc) # TODO! Translate this!
              # http://stackoverflow.com/a/696095/1008905
              raise WrappedException, (msg, exc_type, exc_value), exc_trace
            except Exception, exc:
              response = exception_handler(exc, context)
              return response

        # Add some additional information to the response-data
        if view:
            data['view'] = view.__class__.__name__

        if context.get('kwargs', None):
            data['kwargs'] = context['kwargs']

        if request.data:
            data['request'] = request.data

        if not status_code:
          status_code = exc.status_code if exc.status_code else 500

        set_rollback()
        return Response(data, status=status_code)
예제 #2
0
def get_exception_handler(exc, context=None):
    """
    `exception_handler` did not accept context as an argument prior to DRF 3.1.
    """
    from rest_framework.views import exception_handler
    if len(inspect.getargspec(exception_handler)[0]) == 2:
        return exception_handler(exc, context)
    else:
        return exception_handler(exc)
예제 #3
0
def api_exception_handler(exc, context=None):
    response = exception_handler(exc, context) if context else exception_handler(exc)

    if response is not None and hasattr(response, "data"):
        if hasattr(exc, "errno"):
            response.data["errno"] = exc.errno
        else:
            response.data["errno"] = -1

    return response
예제 #4
0
def custom_exception_handler(exc, context=None):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    if DJANGO_VERSION[0] >= 1 and DJANGO_VERSION[1] >= 7:
    	response = exception_handler(exc, context)
    else: 
    	response = exception_handler(exc, context)
    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status_code'] = response.status_code

    return response
예제 #5
0
파일: helpers.py 프로젝트: alpayOnal/flj
def my_exception_handler(exc, context):
    if (
                isinstance(exc, exceptions.APIException) and
                isinstance(exc.detail, (list, dict))
    ):
        detail = " - ".join(
            ["{}: {}".format(k, v[0]) for k, v in exc.detail.items()])
        response = {"error": detail}
        set_rollback()
        return Response(response, status=exc.status_code)
    else:
        exception_handler(exc, context)
def customer_exception_handler(exc, context):
    """
    customer exception handler

    :param exc:
    :param context:
    :return:
    """

    response = exception_handler(exc, context)

    # customer one
    if isinstance(exc, DBRelyOnException) or \
        isinstance(exc, DBIntegrityException) or \
        isinstance(exc, DBFieldLengthException) or \
        isinstance(exc, ParamNotEnoughException) or \
        isinstance(exc, ParamTypeException) or \
        isinstance(exc, ObjectNotExistException) or \
        isinstance(exc, OffsetOutOfRangeException):
        response = Response(
            exc.__dict__,
            status=status.HTTP_400_BAD_REQUEST
        )

    # add response filter here

    # return default one
    return response
예제 #7
0
 def __new__(self, exc, context):
     response = exception_handler(exc, context)
     error_logger.error(exc)
     if response is not None:
         return ErrorResponse(status=response.status_code,
                              message=exc.message)
     return ErrorResponse(message="An unexpected error occurred. Please try again.")
예제 #8
0
def custom_exception_handler(exc, context=None):
    """
    Custom exception handler for DRF, which ensures every exception we throw
    is caught, returned as a nice DRF Response, while still going to sentry
    etc.

    The default DRF exception handler does some of this work already, but it
    lets non-api exceptions through, and we don't want that.
    """
    # If propagate is true, bail early.
    if settings.DEBUG_PROPAGATE_EXCEPTIONS:
        raise

    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # If the response is None, then DRF didn't handle the exception and we
    # should do it ourselves.
    if response is None:
        # Start with a generic default error message.
        data = {'detail': 'Internal Server Error'}

        # Send the got_request_exception signal so other apps like sentry
        # are aware of the exception. The sender does not match what a real
        # exception would do (we don't have access to the handler here) but it
        # should not be an issue, what matters is the request.
        request = context.get('request')
        sender = context.get('view').__class__
        got_request_exception.send(sender, request=request)

        # Send the 500 response back.
        response = Response(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    return response
예제 #9
0
def json_api_exception_handler(exc, context):
    """ Custom exception handler that returns errors object as an array """

    # Import inside method to avoid errors when the OSF is loaded without Django
    from rest_framework.views import exception_handler
    response = exception_handler(exc, context)

    # Error objects may have the following members. Title removed to avoid clash with node "title" errors.
    top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
    errors = []

    if response:
        message = response.data

        if isinstance(message, dict):
            for error_key, error_description in message.iteritems():
                if error_key in top_level_error_keys:
                    errors.append({error_key: error_description})
                else:
                    if isinstance(error_description, basestring):
                        error_description = [error_description]
                    errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason}
                                   for reason in error_description])
        else:
            if isinstance(message, basestring):
                message = [message]
            errors.extend([{'detail': error} for error in message])

        response.data = {'errors': errors}

    return response
예제 #10
0
def mhacks_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    if not response:
        return response
    if isinstance(response.data, str):
        response.data = {'detail': response}
    elif isinstance(response.data, list):
        response.data = {'detail': response.data[0]}
    elif not response.data.get('detail', None):
        if len(response.data) == 0:
            response.data = {'detail': 'Unknown error'}
        elif isinstance(response.data, list):
            response.data = {'detail': response.data[0]}
        elif isinstance(response.data, dict):
            first_key = response.data.keys()[0]
            detail_for_key = response.data[first_key]
            if isinstance(detail_for_key, list):
                detail_for_key = detail_for_key[0]
            if first_key.lower() == 'non_field_errors':
                response.data = {'detail': "{}".format(detail_for_key)}
            else:
                response.data = {'detail': "{}: {}".format(first_key.title(), detail_for_key)}
        else:
            response.data = {'detail': 'Unknown error'}
    return response
예제 #11
0
def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)
    res = {}

    if response is not None:
        if response.status_code != 200:
            if 'detail' in response.data:
                response.data['error'] = response.data['detail']
                response.data.pop('detail')
            else:
                for k,v in response.data.items():
                    if isinstance(response.data[k], list):
                        res[k] = response.data[k]
                        response.data.pop(k)
                    else:
                        res.update(v)
                        response.data.pop(k)

                response.data['error'] = res

                #     if isinstance(response.data[k], dict):
                #         # response.data.update(v)
                #         res.update(v)
                #         response.data['error'] = res
                #         response.data.pop(k)
                #     else:
                #         response.data['error'] = 'trace'#response.data[k]
                #         # response.data[k] = response.data[k]


            # response.data['error']  = response.data['detail'] if 'detail' in response.data else dict((k) for k in response.data.items())
            # response.data.pop('detail') if 'detail' in response.data else [response.data.pop(k) for k in response.data if k != 'error']

    return response
예제 #12
0
def custom_exception_handler(exc, context):
    """An example handler for custom exceptions that aren't taken care of by
     DRF.

    :param exc: An exception
    :type exc: Exception

    """

    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # All other generated exceptions should be logged and handled here.
    if response is None:
        if isinstance(exc, elasticsearch.exceptions.ElasticsearchException) or\
           isinstance(exc, elasticsearch.exceptions.ImproperlyConfigured):

            response = es_custom_exception_handler(exc)

        elif isinstance(exc, Exception):
            data = {'detail': "There was an error processing this request. ",
                    'message': exc.message}
            response = Response(data,
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            # not an exception
            return None

    return response
예제 #13
0
def custom_exception_handler(exc):
    '''
        自定义异常handler
        django rest 的异常返回为{'detail': 'Error message'}
        我们需求的异常返回为{
            'message': 'Error message',
            'errors': {
                'email': 'missing',
            },
        }
        missing: 这意味着资源不存在
        missing_field: 这意味着对资源所需的领域尚未确定
        invalid: 这意味着领域格式不合法。资源文档应该给您提供更专业的信息。
        already_exists: 这意味着已经存在和该领域同样值的资源了。这就要求要有独立的key
    '''

    # 获取django标准的异常response
    response = exception_handler(exc)
    if response is not None:
        message = response.data.get('detail', '')
        errors = {}
        if message.startswith('errors||'):
            errors = json.loads(message.split('||')[1])
            message = 'Validation Failed'
        response.data = {'message': message, 'errors': errors}
        return response
예제 #14
0
def custom_exception_handler(exc, context):
    """
    Django Restframework fails silently to the errors it doesn't handle.
    This handler will bubble up errors that are not handled by DRF.
    Users of this handler will have to catch the error themselves..
    ..NOTE : ValidationErrors esp django model errors are context specific
    hence handling them here will provide a generic message that won't
    be helpful for that context..therefore they are better handled by the
    users themselves.
    """

    response = exception_handler(exc, context)
    if response:
        return response

    if isinstance(exc, ValidationError):
        LOGGER.error(exc)
        return Response(exc, status=status.HTTP_400_BAD_REQUEST)
    else:
        data = {'detail': ['Server Error: {}'.format(exc.__class__.__name__)]}

        # Keep this or you'll pull your hair out when **** hits the fan
        import traceback
        traceback.print_exc()
        LOGGER.error(exc)
        return Response(data, status=500)
예제 #15
0
파일: exceptions.py 프로젝트: decko/procult
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data = {}
        errors = {}
        if isinstance(exc, Http404):
            response.data['errors'] = [
                "Registro não encontrado. Verifique se não foi removido."
            ]
        else:
            if isinstance(exc.detail, list):
                errors['message'] = exc.detail[0]
            else:
                for field, value in exc.detail.items():
                    if isinstance(value, list):
                        errors[field] = value[0]
                    elif isinstance(value, OrderedDict):
                        _iter_errors_dict(value, errors)
                    elif isinstance(value, str):
                        errors[field] = value
            response.data['errors'] = errors

        response.data['status'] = response.status_code

    return response
def rest_exception_handler(exc, context):
    # Let builtin exception handler process first
    # This will handle 404, 403, and general APIException
    response = exception_handler(exc, context)

    if response:
        reason = exc.__class__.__name__
        entity = {'status': 'error'}

        # Find the error code if available
        if isinstance(exc, APIException):
            reason = exc.get_codes()
            entity['code'] = unwrap(reason)

        # Wraps the response data if it is not in `dict`
        if not isinstance(response.data, dict):
            entity['detail'] = unwrap(response.data)
            response.data = entity

        # ValidationError returns `dict` but not in our favor
        elif isinstance(exc, ValidationError):
            entity['code'] = 'params_invalid'
            entity['detail'] = response.data
            response.data = entity
        else:
            response.data.update(entity)

        # Log our own error and set expectable status field
        logger.info('Status code %s, reason %s', response.status_code, reason)

    return response
예제 #17
0
파일: exceptions.py 프로젝트: sbt9uc/osf.io
def json_api_exception_handler(exc, context):
    """ Custom exception handler that returns errors object as an array """

    # Import inside method to avoid errors when the OSF is loaded without Django
    from rest_framework.views import exception_handler

    response = exception_handler(exc, context)

    # Error objects may have the following members. Title removed to avoid clash with node "title" errors.
    top_level_error_keys = ["id", "links", "status", "code", "detail", "source", "meta"]
    errors = []

    if response:
        message = response.data
        if isinstance(message, dict):
            for key, value in message.iteritems():
                if key in top_level_error_keys:
                    errors.append({key: value})
                else:
                    if isinstance(value, list):
                        for reason in value:
                            errors.append({"detail": reason, "meta": {"field": key}})
                    else:
                        errors.append({"detail": value, "meta": {"field": key}})
        elif isinstance(message, (list, tuple)):
            for error in message:
                errors.append({"detail": error})
        else:
            errors.append({"detail": message})

        response.data = {"errors": errors}

    return response
예제 #18
0
def custom_exception_handler(exc, context):
    """Return a response from customized exception handling.

    :param exc: An exception
    :type exc: Exception

    """

    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # All other generated exceptions should be logged and handled here.
    if response is None:
        if isinstance(exc, elasticsearch.exceptions.ElasticsearchException) or\
           isinstance(exc, elasticsearch.exceptions.ImproperlyConfigured):

            response = es_custom_exception_handler(exc)

        elif isinstance(exc, Exception):
            data = {'detail': "There was an error processing this request. "
                              "Please file a ticket with support.",
                    'message': str(exc)}
            logger.exception(exc)
            response = Response(data,
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            # not an exception
            return None

    return response
예제 #19
0
def rest_exception_handler(exc):
    response = exception_handler(exc)

    if response is not None:
        response.data['__all__'] = [response.data['detail']]

    return response
예제 #20
0
def custom_exception_handler(exc):
    """
    Custom exception handler for DRF, which doesn't provide one for HTTP
    responses like tastypie does.
    """
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc)

    # If the response is None, then DRF didn't handle the exception and we
    # should do it ourselves.
    if response is None:
        # Start with a generic default error message.
        data = {"detail": "Internal Server Error"}

        # Include traceback if DEBUG is active.
        if settings.DEBUG:
            import traceback
            import sys

            data['error_message'] = unicode(exc)
            data['traceback'] = '\n'.join(
                traceback.format_exception(*(sys.exc_info())))

        request = getattr(exc, '_request', None)
        klass = getattr(exc, '_klass', None)

        # Send the signal so other apps are aware of the exception.
        got_request_exception.send(klass, request=request)

        # Send the 500 response back.
        response = Response(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    return response
예제 #21
0
파일: exceptions.py 프로젝트: Junar/datal
def datal_exception_handler(exception, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exception, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status'] = response.status_code
        if not 'description' in response.data:
            response.data['description'] = ''
            if 'detail' in response.data:
                response.data['description'] =  response.data.pop('detail')
        response.data['error'] = str(exception.__class__.__name__)
        response.data['type'] = 'api-error'
    elif isinstance(exception, DATALException):
        set_rollback()
        response = Response({}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        response.data['status'] = exception.status_code
        response.data['description'] =  exception.description % {}
        response.data['error'] = str(exception.__class__.__name__)
        response.data['type'] = exception.tipo
    elif not settings.DEBUG:
        logger = logging.getLogger(__name__)
        trace = '\n'.join(traceback.format_exception(*(sys.exc_info())))
        logger.error('[UnexpectedCatchError] %s. %s %s' % (
                str(exception), repr(exception), trace))
        set_rollback()
        response = Response({}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        response.data['status'] = response.status_code
        response.data['description'] = str(exception)
        response.data['error'] = str(exception.__class__.__name__)
        response.data['type'] = 'unexpected-error'

    return response
예제 #22
0
def custom_exception_handler(exc):
    """
    Formats REST exceptions like:
    {
        "error": "error_code",
        "error_description": "description of the error",
    }
    :param exc: Exception
    :return: Response
    """
    response = exception_handler(exc)

    if not response:
        # Unhandled exceptions (500 internal server errors)
        response = Response(data={
            'error': 'server_error',
            'error_description': unicode(exc),
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        return response

    if hasattr(exc, 'default_error'):
        response.data['error'] = exc.default_error
    else:
        response.data['error'] = 'api_error'

    if hasattr(exc, 'default_detail'):
        response.data['error_description'] = exc.default_detail
    elif 'detail' in response.data:
        response.data['error_description'] = response.data['details']

    if 'detail' in response.data:
        del response.data['detail']

    return response
예제 #23
0
파일: utils.py 프로젝트: harvard-lil/perma
def dispatch_multiple_requests(request, call_list, custom_request_attributes=None):
    """
    Makes a series of internal api "calls" on behalf of a user,
    all within a single http request/response cycle.

    The first argument should be the Django request object from the initiating
    api call.

    The call_list should be series of dictionaries specifying:
        "path", the api route to "call" (e.g. /v1/folders/22/archives/)
        "verb", the http verb to use (e.g. "GET")
        (optional)
        "data": a dictionary of data to send with the request,
                i.e., the data that would normally be sent as JSON
                when hitting the api route

    If you need to customize the request object passed to the
    api's view function, pass a dict of attribute/value pairs.
    For example, {"parent": 1} will set request.parent = 1 on
    every generated request object.

    A list of dictionaries will be returned reporting:
        "status_code": the http status code returned by the "call"
        "status_text": the text associated with the http status code
        "data": the data returned by the call, i.e., the data that would
                normally be converted to JSON and transmitted as the http body
    """
    factory = APIRequestFactory()
    responses = []
    for call in call_list:
        try:
            view, args, kwargs = resolve(call['path'])
            new_request = getattr(factory, call['verb'].lower())(call['path'], data=call.get('data', {}))
            new_request.user = request.user
            new_request.META['HTTP_HOST'] = request._get_raw_host()
            if custom_request_attributes:
                for attribute, value in custom_request_attributes.items():
                    setattr(new_request, attribute, value)
            response = view(new_request, *args, **kwargs)
        except Exception as exception:
            response = exception_handler(exception, {})
            if not response:
                logger.exception("Internal Server Error")
                class SpoofResponse:
                    pass
                response = SpoofResponse()
                response.status_code = 500
                response.status_text = 'Internal Server Error',
                response.data = {
                    'path': call['path'],
                    'verb': call['verb'],
                    'data': call['data']
                }
        responses.append({
            'status_code': response.status_code,
            'status_text': response.status_text,
            'data': response.data
        })
    return responses
예제 #24
0
def custom_exception_handler(exc, context):
    if isinstance(exc, exceptions.ValidationError):
        exc.detail = {
                'data': exc.detail,
                'detail': 'Unfortunately, there are some problems with the data you committed'
            }

    return exception_handler(exc, context)
예제 #25
0
def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    # We overwrite the response status code to 500
    if response is not None:
        return Response({'detail': str(exc)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    return response
예제 #26
0
def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    # TODO: Error handling
    if response is not None:
        response.data['error'] = 7

    return response
예제 #27
0
def QnAExceptionHandler(exc):
    # REST framework's default exception handler
    response = exception_handler(exc)

    if response is not None:
        response.data['status_code'] = response.status_code

    return response
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)
    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['code'] = response.status_code

    return response
예제 #29
0
def greedy_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.

    response = exception_handler(exc, context)
    # Now add the HTTP status code to the response.
    if response and response.status_code in [400, 401, 403, 404, 500, 405]:
        response.data['status'] = "error"
    return response
예제 #30
0
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    print exc
    print context

    return response
예제 #31
0
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        # Make sure the message gets in the "data" property
        # and the status in the "status" property.
        response = Response(data=str(response.data),
                            status=response.status_code)
    else:
        # Create a new Response from scratch.
        response = Response(data=str(exc), status=status.HTTP_400_BAD_REQUEST)

    return response
예제 #32
0
def api_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    from rest_framework.views import exception_handler
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data = {
            'code': response.status_code,
            'detail': response.reason_phrase
        }
        if hasattr(exc, 'detail'):
            response.data['detail'] = exc.detail

    return response
예제 #33
0
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status_code'] = response.status_code
        response = Response(response.data)
    else:
        pass
        # if isinstance(exc, DatabaseError):
        #     response = Response({'detail': 'Database Error'})
        # else:
        #     response = Response({'detail': 'Other Error'})
    return response
예제 #34
0
def api_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response is not None:
        if len(response.data) == 1 and 'detail' in response.data:
            response.data['message'] = response.data['detail']
            response.data.pop('detail')
        else:
            response.status_code = 422  # 验证错误, 参考:http://tools.ietf.org/html/rfc4918#section-11.2
            origin_data = response.data
            response.data = {
                'message': '验证错误',
                'errors': origin_data,
            }

    return response
예제 #35
0
def handle_non_field_error(exc, context):
    """
    Handle the given WsRestNonFieldException and return a response.
    :param exc: The exception that was thrown.
    :param context: The context in which the exception was thrown.
    :return: A Django Response object.
    """
    response = exception_handler(exc, context)
    response.status_code = 400
    response.data = {
        "status_code": 400,
        "message": "Invalid input received.",
        "detail": exc.detail,
        "error_fields": [],
    }
    return response
예제 #36
0
def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response is not None:
        if isinstance(context['view'], LoginView):
            # 登陆失败
            if isinstance(exc, exceptions.AuthenticationFailed):
                response.status_code = 200
                response.data['status'] = 'loginError'
                response.data['currentAuthority'] = 'guest'
                del response.data['detail']

        if hasattr(context['view'].__class__, 'handle_err_response'):
            response = context['view'].__class__.handle_err_response(
                exc, context, response)
    return response
예제 #37
0
def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response:
        # Handle a rare case where response.data will be a list object
        # instead of a dict because a ValidationError was raised
        if isinstance(exc, rest_framework.exceptions.ValidationError):
            details = {"detail": exc.get_full_details()}
            response.data = details

        response.data["status_code"] = getattr(response, "status_code", 500)

        if isinstance(exc, APIException):
            response.data["code"] = exc.get_codes()

    return response
예제 #38
0
def core_exception_handler(exc, context):
    """
    If an exception is thrown that we don't explicitly handle here, we want
    to delegate to the default exception handler offered by DRF. If we do
    handle this exception type, we will still want access to the response
    generated by DRF, so we get that response up front.
    """
    response = exception_handler(exc, context)
    handlers = {'ValidationError': _handle_generic_error}

    exception_class = exc.__class__.__name__

    if exception_class in handlers:
        return handlers[exception_class](exc, context, response)

    return response
예제 #39
0
def custom_exception_handler(exc, context):

    response = exception_handler(exc, context)

    # if response is not None:
    #     response.data['status_code'] = response.status_code

    try:
        # if exc.pk:
        #     response.data['pk'] = exc.pk
        if exc.key and exc.value:
            response.data[exc.key] = exc.value
    # except AttributeError:
    #     return response
    finally:
        return response
예제 #40
0
def base_exception_handler(exc, context):
    # Call DRF's default exception handler first,
    # to get the standard error response.

    response = exception_handler(exc, context)
    errors = {}

    # check that a DRFValidationError exception is raised
    if isinstance(exc, DRFValidationError):
        # here prepare the 'custom_error_response' and
        # set the custom response data on response object
        errors["errors"] = construct_validation_error_response(exc, response)

    if response:
        response.data = errors
    return response
예제 #41
0
파일: views.py 프로젝트: 7253641/comses.net
def rest_exception_handler(exc, context):
    request = context.get('request')
    logger.warning("DRF exception handler %s", exc, exc_info=True)
    if request and request.accepted_media_type == 'text/html':
        if isinstance(exc, (Http404, NotFound)):
            return page_not_found(request, exc, context=context)
        elif isinstance(
                exc,
            (PermissionDenied, DrfPermissionDenied, NotAuthenticated)):
            return permission_denied(request, exc, context=context)
        elif isinstance(exc, APIException) and 400 <= exc.status_code <= 500:
            return other_400_error(request, exc, context=context)
        else:
            return server_error(request, context=context)
    else:
        return exception_handler(exc, context)
예제 #42
0
def core_exception_handler(exc, context):
    # If an exception is thrown that we don't explicitly handle here, we want
    # to delegate to the default exception handler offered by DRF. If we do
    # handle this exception type, we will still want access to the response
    # generated by DRF, so we get that response up front.
    response = exception_handler(exc, context)
    handlers = {
        'NotFound': _handle_not_found_error,
        'ValidationError': _handle_generic_error,
    }
    # This is how we identify the type of the current exception. We will use
    # this in a moment to see whether we should handle this exception or let
    # Django REST Framework do it's thing.
    exception_class = exc.__class__.__name__

    return handlers.get(exception_class,_default_error)(exc, context, response)
예제 #43
0
def expected_error_exception_handler(exc, context):
    """
    Replacement for DRF's default exception handler to enable observing expected errors.

    In addition to the default behaviour, add logging and monitoring for expected errors.
    """
    # Call REST framework's default exception handler first to get the standard error response.
    response = exception_handler(exc, context)

    try:
        request = context['request'] if 'request' in context else None
    except TypeError:  # when context is not iterable
        request = None

    _log_and_monitor_expected_errors(request, exc, 'drf')
    return response
예제 #44
0
파일: base.py 프로젝트: itsb/alyx
def rest_filters_exception_handler(exc, context):
    """
    Custom exception handler that provides context (field names etc...) for poorly formed
    REST queries
    """
    response = exception_handler(exc, context)

    from rest_framework.response import Response
    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status_code'] = response.status_code
    else:
        data = {'status_code': 500, 'detail': str(exc)}
        response = Response(data, status=500)

    return response
예제 #45
0
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.

    try:
        if response.data['non_field_errors']:
            response.data['msg'] = "Login failed invalid credentials"
            response.data['status'] = 0
            del response.data['non_field_errors']
    except Exception as e:
        pass

    return response
예제 #46
0
파일: utils.py 프로젝트: vikash979/drfapi3
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status_code'] = response.status_code

    print("response.data",response.data)
    data = {}
    data['status'] = 0
    data['data'] =[]
    data['errors'] = [response.data.get('detail')]
    response.data = data
    return response
예제 #47
0
def custom_exception_handler(exc, context):
    """ Make custom exception treatment in RestFramework

    :param exc: Exception - you can check specific exception
    :param context: context
    :return: response with error desc
    """
    exception_id = uuid.uuid4()
    logger.error('{} {}'.format(exception_id, exc), exc_info=True)

    exc = _override_exceptions(exc)

    # error body structure
    response_data = {
        'id': exception_id,
        'status_code': status.HTTP_500_INTERNAL_SERVER_ERROR,  # default value
        'version': label_studio.__version__,
        'detail': 'Unknown error',  # default value
        'exc_info': None,
    }
    # try rest framework handler
    response = exception_handler(exc, context)
    if response is not None:
        response_data['status_code'] = response.status_code

        if 'detail' in response.data and isinstance(response.data['detail'], ErrorDetail):
            response_data['detail'] = response.data['detail']
            response.data = response_data
        # move validation errors to separate namespace
        else:
            response_data['detail'] = 'Validation error'
            response_data['validation_errors'] = response.data if isinstance(response.data, dict) else {'non_field_errors': response.data}
            response.data = response_data

    # non-standard exception
    elif sentry_sdk_loaded:
        # pass exception to sentry
        set_tag('exception_id', exception_id)
        capture_exception(exc)

        exc_tb = tb.format_exc()
        logger.debug(exc_tb)
        response_data['detail'] = str(exc)
        response_data['exc_info'] = exc_tb
        response = Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR, data=response_data)

    return response
예제 #48
0
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # 扩展原来的exception, 添加error_code

    if isinstance(exc, Http404):
        response.data['error_code'] = 2

    elif isinstance(exc, exceptions.NotFound):
        response.data['error_code'] = 2

    elif isinstance(exc, exceptions.MethodNotAllowed):
        response.data['error_code'] = 3

    elif isinstance(exc, exceptions.NotAcceptable):
        response.data['error_code'] = 4

    elif isinstance(exc, exceptions.Throttled):
        response.data['error_code'] = 5

    elif isinstance(exc, exceptions.ParseError):
        response.data['error_code'] = 10

    elif isinstance(exc, exceptions.ValidationError):
        response.data['error_code'] = 11

    elif isinstance(exc, exceptions.UnsupportedMediaType):
        response.data['error_code'] = 12

    elif isinstance(exc, extra_exceptions.ItemExists):
        response.data['error_code'] = 13

    elif isinstance(exc, extra_exceptions.ItemDoesNotExist):
        response.data['error_code'] = 14

    elif isinstance(exc, PermissionDenied):
        response.data['error_code'] = 20

    elif isinstance(exc, exceptions.AuthenticationFailed):
        response.data['error_code'] = 21

    elif isinstance(exc, exceptions.NotAuthenticated):
        response.data['error_code'] = 22

    return response
예제 #49
0
def custom_exception_handler(exc, context):
	# Call REST framework's default exception handler first,
	# to get the standard error response.
	response = exception_handler(exc, context)
	if isinstance(exc, Http404):
		response.data = {}
		errors = ["Not Found : Resource does not exist"]
		response.data['errors'] = errors
		response.data['status_code'] = 404
		return response

	if isinstance(exc, rest_framework_simplejwt.exceptions.InvalidToken):
		response.data = {}
		errors = ["Invalid Token : Given token is not valid"]
		response.data['errors'] = errors
		response.data['status_code'] = 401
		return response
	if isinstance(exc, exceptions.NotAuthenticated):
		response.data = {}
		errors = ["Unauthorized : Authentication not provided."]
		response.data['errors'] = errors
		response.data['status_code'] = 401
		return response
	if isinstance(exc, exceptions.PermissionDenied):
		response.data = {}
		errors = 'Forbidden : You do not have necessary permissions'
		response.data['errors'] = errors
		response.data['status_code'] = 403

	"""
	if response is not None:
		# check if exception has dict items
		if hasattr(exc.detail, 'items'):
			# remove the initial value
			response.data = {}
			errors = []
			for key, value in exc.detail.items():
				# append errors into the list
				errors.append("{} : {}".format(key, "".join(value)))

			# add property errors to the response
			response.data['errors'] = errors

		# serve status code in the response
		response.data['status_code'] = response.status_code
	"""
	return response
예제 #50
0
def custom_exception_handler(exc, context):
    """
    Call REST framework's default exception handler first,
    to get the standard error response.
    """

    helper = ["detail", "phone", "full_name", "photo", "passcode"]

    response = exception_handler(exc, context)
    # Now add the HTTP status code to the response.
    if response is not None:
        try:
            exception = exc.detail
        except:
            response.data['details'] = str(exc)
            response.data['status'] = 404
        else:
            error = {}  # default errors obj
            response.data['error'] = True

            if 'non_field_errors' in exception:
                details = exception.pop('non_field_errors')
                error['non_field_errors'] = _(details)

            if 'detail' in response.data:
                _detail = response.data.pop('detail')
                if isinstance(_detail, list):
                    error = _(_detail[0])
                else:
                    error = _(_detail)
            else:
                # Check models and serializers fields' errors
                key_fields = list(exception.keys())
                for key_field in key_fields:
                    if key_field in helper:
                        key_error = response.data.pop(key_field)
                        if isinstance(key_error, list):
                            error[key_field] = _(key_error[0])
                        else:
                            error[key_field] = _(key_error)

            response.data['details'] = error
            response.data['status'] = int(
                exception['status']
            ) if "status" in exception else response.status_code

    return response
예제 #51
0
def json_api_exception_handler(exc, context):
    """
    Custom exception handler that returns errors object as an array
    """

    # We're deliberately not stripping html from exception detail.
    # This creates potential vulnerabilities to script injection attacks
    # when returning raw user input into error messages.
    #
    # Fortunately, Django's templating language strips markup bu default,
    # but if our frontend changes we may lose that protection.
    # TODO: write tests to ensure our html frontend strips html

    # Import inside method to avoid errors when the OSF is loaded without Django
    from rest_framework.views import exception_handler

    response = exception_handler(exc, context)

    errors = []

    if response:
        message = response.data

        if isinstance(exc, TwoFactorRequiredError):
            response['X-OSF-OTP'] = 'required; app'

        if isinstance(exc, JSONAPIException):
            errors.extend([{
                'source': exc.source or {},
                'detail': exc.detail,
                'meta': exc.meta or {}
            }])
        elif isinstance(message, dict):
            errors.extend(dict_error_formatting(message, context, index=None))
        else:
            if isinstance(message, basestring):
                message = [message]
            for index, error in enumerate(message):
                if isinstance(error, dict):
                    errors.extend(
                        dict_error_formatting(error, context, index=index))
                else:
                    errors.append({'detail': error})

        response.data = {'errors': errors}

    return response
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    if response is not None:
        if isinstance(exc, ParseError):
            retdata = BaseResponse(
                code=0,
                msg='error',
                error_msg='JSON数据不合法'
            )
            return Response(retdata.result)

        if isinstance(exc, MethodNotAllowed):
            retdata = BaseResponse(
                code=0,
                msg='error',
                error_msg='当前请求方法不被允许'
            )
            return Response(retdata.result)

        if isinstance(exc, Throttled):
            retdata = BaseResponse(
                code=0,
                msg='error',
                error_msg='请求过于频繁, 请于{seconds}秒后重试'.format(seconds=exc.wait)
            )
            return Response(retdata.result)

        if isinstance(exc, AuthenticationFailed) or isinstance(exc, NotAuthenticated):
            retdata = BaseResponse(
                code=0,
                msg='error',
                error_msg='认证失败,请提供正确的认证Token'
            )
            return Response(retdata.result)

        if isinstance(exc, UnsupportedMediaType):
            retdata = BaseResponse(
                code=0,
                msg='error',
                error_msg='不支持的MediaType'
            )
            return Response(retdata.result)

    return response
예제 #53
0
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        # print("res  data:", response.data)
        # print("response", response)
        # print(type(response.data))
        # print(str(response.data))
        from rest_framework.renderers import JSONRenderer
        jr = json.loads(str(JSONRenderer().render(response.data), encoding='utf-8'))

        response.data.clear()
        response.data['code'] = response.status_code

        try:
            response.data['data'] = {k: v[0] for k, v in jr.items()}
        except Exception as e:
            response.data['data'] = []

        if response.status_code == 404:
            try:
                response.data['message'] = response.data.pop('detail')
                response.data['message'] = "Not found"
            except KeyError:
                response.data['message'] = "Not found"

        if response.status_code == 400:
            response.data['message'] = 'Input error'

        elif response.status_code == 401:
            response.data['message'] = "Auth failed"

        elif response.status_code >= 500:
            response.data['message'] = "Internal service errors"

        elif response.status_code == 403:
            response.data['message'] = "Access denied"

        elif response.status_code == 405:
            response.data['message'] = 'Request method error'
        response.code = response.status_code
        response.status_code = 200
    # return Response({'data':  response.data})
    return Response(response.data)
예제 #54
0
def json_root_object_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)
    # If exception_handler returns None, the exception has not been handled by rest_framework
    # If we return None, Django responds with a 500 (and html in debug mode). So we should handle them and
    # return appropriate responses. For now, we'll just return None from the handler to aid ongoing development
    if response is None:
        return None
    # response.data may be list or a single object
    if isinstance(response.data, list):
        errors = [make_json_root_error(response.status_code, data, exc) for data in response.data]
    else:
        errors = [make_json_root_error(response.status_code, response.data, exc)]

    response.data = {'errors': errors}
    return response
예제 #55
0
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    if response:
        final_response = {
            "error": {
                "field_errors": {},
                "non_field_errors": []
            }
        }
        final_response['error']['field_errors'] = response.data

        response.data = final_response

    return response
예제 #56
0
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)
    if response is not None:
        response.data = {}
        errors = []
        for field, value in response.data.items():
            errors.append("{} : {}".format(field, " ".join(value)))

        response.data['errors'] = errors
        response.data['status'] = False
        response.data['message'] = 'failed'

        response.data['exception'] = str(exc)

    return response
예제 #57
0
def temba_exception_handler(exc, context):
    """
    Custom exception handler which prevents responding to API requests that error with an HTML error page
    """
    from rest_framework.views import exception_handler

    response = exception_handler(exc, context)

    if response or not getattr(settings, "REST_HANDLE_EXCEPTIONS", False):
        return response
    else:
        # ensure exception still goes to Sentry
        logger.error("Exception in API request: %s" % str(exc), exc_info=True)

        # respond with simple message
        return HttpResponseServerError(
            "Server Error. Site administrators have been notified.")
예제 #58
0
def base_exception_handler(exc, context):
    # Call DRF's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # check that a ValidationError exception is raised
    if isinstance(exc, ValidationError):
        # here prepare the 'custom_error_response' and
        # set the custom response data on response object
        if response.data.get('username', None):
            response.data = response.data['username'][0]
        elif response.data.get('email', None):
            response.data = response.data['email'][0]
        elif response.data.get('password', None):
            response.data = response.data['password'][0]

    return response
def model_exception_handler(exc, context):
    """Catches django.core exceptions and standard python exceptions from the
    model level and converts them to a DRF Response object. All other
    exceptions are ignored and return as usual"""
    response = exception_handler(exc, context)
    if response:
        if (isinstance(response.data, list) or
           'detail' not in response.data.keys()):
            response.data = {'detail': parse_error_messages(response.data)}
    else:
        msg = exc.message
        if not msg and hasattr(exc, 'messages'):
            msg = '; '.join(exc.messages)
        response = Response(
            status=status.HTTP_400_BAD_REQUEST, data={'detail': msg}
        )
    return response
예제 #60
0
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Update the structure of the response data.
    if response is not None:
        customized_response = {}
        customized_response['errors'] = []

        for key, value in response.data.items():
            error = {'field': key, 'message': value}
            customized_response['errors'].append(error)

        response.data = customized_response

    return response