Python rest_framework.views 模块,exception_handler() 实例源码

我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用rest_framework.views.exception_handler()

项目:django-realworld-example-app    作者:gothinkster    | 项目源码 | 文件源码
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__

    if exception_class in handlers:
        # If this exception is one that we can handle, handle it. Otherwise,
        # return the response generated earlier by the default exception 
        # handler.
        return handlers[exception_class](exc, context, response)

    return response
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
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.captureException()

        formatted_exception_string = "{0}: {1}".format(type(exc).__name__, str(exc))
        return Response(
            status=status.HTTP_500_INTERNAL_SERVER_ERROR,
            data=[formatted_exception_string]
        )
项目:drf-friendly-errors    作者:FutureMind    | 项目源码 | 文件源码
def friendly_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if not response and settings.CATCH_ALL_EXCEPTIONS:
        exc = APIException(exc)
        response = exception_handler(exc, context)

    if response is not None:
        if is_pretty(response):
            return response
        error_message = response.data['detail']
        error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
            exc.__class__.__name__)
        response.data.pop('detail', {})
        response.data['code'] = error_code
        response.data['message'] = error_message
        response.data['status_code'] = response.status_code
        # response.data['exception'] = exc.__class__.__name__

    return response
项目:munch-core    作者:crunchmail    | 项目源码 | 文件源码
def exception_handler(exc, context):
    # Replace the POST data of the Django request with the parsed
    # data from the DRF
    # Necessary because we cannot read request data/stream more than once
    # This will allow us to see the parsed POST params
    # in the rollbar exception log
    # Based on https://github.com/tomchristie/django-rest-framework/pull/1671
    from rest_framework import views
    from django.http.request import QueryDict
    query = QueryDict('', mutable=True)
    try:
        if not isinstance(context['request'].data, dict):
            query.update({'_bulk_data': context['request'].data})
        else:
            query.update(context['request'].data)
        context['request']._request.POST = query
    except:
        pass
    return views.exception_handler(exc, context)
项目:ac-mediator    作者:AudioCommons    | 项目源码 | 文件源码
def custom_exception_handler(exc, context):
    """
    Custom django rest framework exception handler that includes 'status_code' field in the
    responses.
    """
    # Call REST framework's default exception handler first
    response = exception_handler(exc, context)

    # Catch unexpected exceptions
    if response is None:
        if isinstance(exc, Exception):
            data = {'detail': 'A server error occurred.'}
            set_rollback()
            response = Response(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status_code'] = response.status_code
    return response
项目:issue-reporting    作者:6aika    | 项目源码 | 文件源码
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
项目:Anonymous_message    作者:DevRoss    | 项目源码 | 文件源码
def my_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.
    # print(exc)
    # print(context)
    if response is not None:
        if isinstance(exc, exceptions.AuthenticationFailed):
            response.data['error_code'] = 2
        elif isinstance(exc, exceptions.PermissionDenied):
            response.data['error_code'] = 3
        else:
            response.data['error_code'] = 1
    return response
项目:ws-backend-community    作者:lavalamp-    | 项目源码 | 文件源码
def handle_validation_error(exc, context):
    """
    Handle the given ValidationError 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": "There was an error with the data that you submitted. Please check your input and try again.",
        "error_fields": exc.get_full_details(),
    }
    return response
项目:ws-backend-community    作者:lavalamp-    | 项目源码 | 文件源码
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
项目:kuzgun.io    作者:yigitgenc    | 项目源码 | 文件源码
def custom_exception_handler(exc, context):
    """
    DRF's custom exception handler
    """
    response = exception_handler(exc, context)

    if response is not None:
        # This might be useful for overwriting default error messages. :>
        pass

    return response
项目:parkkihubi    作者:City-of-Helsinki    | 项目源码 | 文件源码
def parkings_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response is not None:
        if isinstance(exc, ParkingException):
            response.data['code'] = exc.get_codes()
        elif isinstance(exc, PermissionDenied):
            response.data['code'] = 'permission_denied'

    return response
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def exception_handler(exc, context):
    response = _handler(exc, context)

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

    return response
项目:django-driver27    作者:SRJ9    | 项目源码 | 文件源码
def custom_exception_handler(exc, context):
    response = rest_exception_handler(exc, context)
    if isinstance(exc, DjangoValidationError):
        data = {'detail': exc.messages}
        set_rollback()
        return Response(data, status=status.HTTP_400_BAD_REQUEST)
    return response
项目:mhacks-admin    作者:mhacks    | 项目源码 | 文件源码
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
项目:momo-wps    作者:WPS-team-4    | 项目源码 | 文件源码
def custom_exception_handler(exc, context):
    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_code'] = '{} - {}'.format(response.status_code, response.status_text)
        response.data['detail'] = str(exc)

    return response
项目:BrewCenterAPI    作者:BrewCenter    | 项目源码 | 文件源码
def custom_exception_handler(exc, context):
    # if its a view with a list and request attr
    if 'view' in context and hasattr(context['view'], 'list') and hasattr(context['view'], 'request'):
        view = context['view']
        request = view.request

        if request.method == 'GET' and settings.ENABLE_UNAUTHENTICATED_RESULTS and isinstance(exc, NotAuthenticated):
            return view.list(context['request'])

    return exception_handler(exc, context)
项目:snippod-starter-demo-app-server    作者:shalomeir    | 项目源码 | 文件源码
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

    return response
项目:django-oauth2-test    作者:ONSdigital    | 项目源码 | 文件源码
def custom_exception_handler(exc, context):
    """
    Formats REST exceptions like:
    {
        "error": "error_code",
        "error_description": "description of the error",
    }
    :param exc: Exception
    :return: Response
    """
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    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
项目:api-django    作者:lafranceinsoumise    | 项目源码 | 文件源码
def exception_handler(exc, context):
    """Custom exception handler

    Returns status code 422 specifically for validation errors

    :param exc:
    :param context:
    :return:
    """
    res = original_exception_handler(exc, context)

    if isinstance(exc, ValidationError):
        res.status_code = 422

    return res
项目:ws-backend-community    作者:lavalamp-    | 项目源码 | 文件源码
def handle_api_exception(exc, context):
    """
    Handle the given APIException.
    :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.data = {
        "status_code": response.status_code,
        "message": "Exception thrown",
        "detail": exc.detail,
        "error_fields": [],
    }
    return response
项目:narwhals    作者:alvaromlg    | 项目源码 | 文件源码
def auth_exception_handler(exc, context):
    response = exception_handler(exc, context)

    # Customized for Android
    if response is not None:
        response.data["success"] = False
        response.data["message"] = response.data["detail"]
        del response.data["detail"]

    return response
项目:InvenTree    作者:inventree    | 项目源码 | 文件源码
def api_exception_handler(exc, context):
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:

        data = {'error': response.data}
        response.data = data

    return response