Python rest_framework.views.exception_handler() Examples

The following are 30 code examples of rest_framework.views.exception_handler(). 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 rest_framework.views , 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: exceptions.py    From resolwe with Apache License 2.0 6 votes vote down vote up
def resolwe_exception_handler(exc, context):
    """Handle exceptions raised in API and make them nicer.

    To enable this, you have to add it to the settings:

        .. code:: python

            REST_FRAMEWORK = {
                'EXCEPTION_HANDLER': 'resolwe.flow.utils.exceptions.resolwe_exception_handler',
            }

    """
    response = exception_handler(exc, context)

    if isinstance(exc, ValidationError):
        if response is None:
            response = Response({})
        response.status_code = 400
        response.data["error"] = exc.message

    return response 
Example #3
Source File: exception.py    From ws-backend-community with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: exception.py    From ws-backend-community with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: exceptions.py    From trace-examples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #6
Source File: exceptions.py    From django-channels-react-multiplayer with MIT License 6 votes vote down vote up
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 
Example #7
Source File: exceptions.py    From cruzz with MIT License 6 votes vote down vote up
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 it, we will still want access to the response
    # generated by DRF, so we get it up front.
    response = exception_handler(exc, context)
    handlers = {
        'ProfileDoesNotExist': _handle_generic_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 its thing.
    exception_class = exc.__class__.__name__

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

    return response 
Example #8
Source File: __init__.py    From notes with GNU General Public License v3.0 6 votes vote down vote up
def drf_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if not response and settings.CATCH_ALL_EXCEPTIONS:
        logging.exception(exc)
        exc = APIException(exc)
        response = exception_handler(exc, context)
    if response is not None:
        response.status_code = HTTP_200_OK
        if is_pretty(response):
            return response
        error_message = response.data.pop('detail', '')
        error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
            exc.__class__.__name__)
        response.data['code'] = error_code
        response.data['message'] = error_message

    return response 
Example #9
Source File: __init__.py    From notes with GNU General Public License v3.0 6 votes vote down vote up
def drf_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if not response and settings.CATCH_ALL_EXCEPTIONS:
        logging.exception(exc)
        exc = APIException(exc)
        response = exception_handler(exc, context)
    if response is not None:
        response.status_code = HTTP_200_OK
        if is_pretty(response):
            return response
        error_message = response.data.pop('detail', '')
        error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
            exc.__class__.__name__)
        response.data['code'] = error_code
        response.data['message'] = error_message

    return response 
Example #10
Source File: exceptions.py    From controller with MIT License 6 votes vote down vote up
def custom_exception_handler(exc, context):
    # give more context on the error since DRF masks it as Not Found
    if isinstance(exc, Http404):
        set_rollback()
        return Response(str(exc), status=status.HTTP_404_NOT_FOUND)

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

    # No response means DRF couldn't handle it
    # Output a generic 500 in a JSON format
    if response is None:
        logging.exception('Uncaught Exception', exc_info=exc)
        set_rollback()
        return Response({'detail': 'Server Error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # log a few different types of exception instead of using APIException
    if isinstance(exc, (DeisException, ServiceUnavailable, HealthcheckException)):
        logging.exception(exc.__cause__, exc_info=exc)

    return response 
Example #11
Source File: exceptions.py    From CTF_AWD_Platform with MIT License 6 votes vote down vote up
def exception_handler(exc, context):
    """
    自定义异常处理
    :param exc: 别的地方抛的异常就会传给exc
    :param context: 字典形式。抛出异常的上下文(即抛出异常的出处;即抛出异常的视图)
    :return: Response响应对象
    """
    # 调用drf框架原生的异常处理方法,把异常和异常出处交给他处理,如果是序列化器异常就直接处理,处理之后就直接返回
    response = drf_exception_handler(exc, context)
	#如果响应为空表示不是序列化器异常,补充数据库异常
    if response is None:
        view = context['view']
        if isinstance(exc, DatabaseError) or isinstance(exc, RedisError):
            # 数据库异常
            logger.error('[%s] %s' % (view, exc))
            response = Response({'message': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

    return response 
Example #12
Source File: exceptions.py    From controller with MIT License 6 votes vote down vote up
def custom_exception_handler(exc, context):
    # give more context on the error since DRF masks it as Not Found
    if isinstance(exc, Http404):
        set_rollback()
        return Response(str(exc), status=status.HTTP_404_NOT_FOUND)

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

    # No response means DRF couldn't handle it
    # Output a generic 500 in a JSON format
    if response is None:
        logging.exception('Uncaught Exception', exc_info=exc)
        set_rollback()
        return Response({'detail': 'Server Error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # log a few different types of exception instead of using APIException
    if isinstance(exc, (DeisException, ServiceUnavailable, HealthcheckException)):
        logging.exception(exc.__cause__, exc_info=exc)

    return response 
Example #13
Source File: views.py    From gro-api with GNU General Public License v2.0 6 votes vote down vote up
def exception_handler(exc, context):
    """
    Django REST handles 4xx exceptions itself, so they don't get logged to the
    'django.request' logger by default. This exception handler logs them as if
    Django was handling them then calls the default Django REST handler. This
    makes the project logging behavior more consistent (both 4xx's and 5xx's
    are sent to the 'django.request' logger)
    """
    res = default_exception_handler(exc, context)
    if res is not None and is_client_error(res.status_code):
        request = context['request']
        logger.warn(
            '%s (params: %s) (data: %s) (response: %s)', request.path,
            request.query_params, request.data, res.data,
            extra={
                'status_code': res.status_code, 'request': request
            }
        )
    return res 
Example #14
Source File: exceptions.py    From aws-workshop with MIT License 6 votes vote down vote up
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 
Example #15
Source File: exception_handler.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def custom_exception_handler(exc, context):
    """Create custom response for exceptions."""
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        errors = []
        data = copy.deepcopy(response.data)
        if isinstance(data, dict):
            errors += _generate_errors_from_dict(data, **{"status_code": response.status_code})
        elif isinstance(data, list):
            errors += _generate_errors_from_list(data, **{"status_code": response.status_code})
        error_response = {"errors": errors}
        response.data = error_response

    return response 
Example #16
Source File: views.py    From safe-relay-service with MIT License 6 votes vote down vote up
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 not response:
        if isinstance(exc, (SafeServiceException, SafeCreationServiceException, TransactionServiceException,
                            FundingServiceException)):
            response = Response(status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        else:
            response = Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        if str(exc):
            exception_str = '{}: {}'.format(exc.__class__.__name__, exc)
        else:
            exception_str = exc.__class__.__name__
        response.data = {'exception': exception_str}

        logger.warning('%s - Exception: %s - Data received %s',
                       context['request'].build_absolute_uri(),
                       exception_str,
                       context['request'].data)
    return response 
Example #17
Source File: handlers.py    From drf-friendly-errors with MIT License 6 votes vote down vote up
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 
Example #18
Source File: exceptionhandler.py    From BrewCenterAPI with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #19
Source File: exceptions.py    From oldp with MIT License 5 votes vote down vote up
def full_details_exception_handler(exc, context):
    """
    This overrides the default exception handler to
    include the human-readable message AND the error code
    so that clients can respond programmatically.
    """
    if isinstance(exc, APIException):
        exc.detail = exc.get_full_details()

    return exception_handler(exc, context) 
Example #20
Source File: services.py    From YaraGuardian with Apache License 2.0 5 votes vote down vote up
def custom_exception_handler(exc, context):
    response_content = {}
    response = exception_handler(exc, context)

    if response is not None:
        response_content['status_code'] = response.status_code
        if 'detail' not in response.data:
            response_content['errors'] = response.data
        else:
            response_content['errors'] = [response.data['detail']]
        response.data = response_content
    return response 
Example #21
Source File: exception.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #22
Source File: views.py    From credentials with GNU Affero General Public License v3.0 5 votes vote down vote up
def credentials_throttle_handler(exc, context):
    """ Exception handler for logging messages when an endpoint is throttled. """
    response = exception_handler(exc, context)

    if isinstance(exc, Throttled):
        view = context['view']
        if isinstance(view, CredentialViewSet):
            view = 'CredentialViewSet'
        elif isinstance(view, GradeViewSet):
            view = 'GradeViewSet'

        log.warning('Credentials API endpoint {} is being throttled.'.format(view))

    return response 
Example #23
Source File: utils.py    From Django-Styleguide with MIT License 5 votes vote down vote up
def exception_errors_format_handler(exc, context):
    response = exception_handler(exc, context)

    # If unexpected error occurs (server error, etc.)
    if response is None:
        return response

    formatter = ErrorsFormatter(exc)

    response.data = formatter()

    return response 
Example #24
Source File: exceptions.py    From django-oauth2-server with Mozilla Public License 2.0 5 votes vote down vote up
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 
Example #25
Source File: misc.py    From karrot-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def custom_exception_handler(exc, context):
    # get the standard response first
    response = exception_handler(exc, context)

    # add in the error code so we can distinguish better in the frontend
    if hasattr(response, 'data') and 'detail' in response.data and hasattr(exc, 'default_code'):
        response.data['error_code'] = exc.default_code

    return response 
Example #26
Source File: exceptions.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def exception_handler(exc, context):
    # Import this here to avoid potential edge-case circular imports, which
    # crashes with:
    # "ImportError: Could not import 'rest_framework_json_api.parsers.JSONParser' for API setting
    # 'DEFAULT_PARSER_CLASSES'. ImportError: cannot import name 'exceptions'.'"
    #
    # Also see: https://github.com/django-json-api/django-rest-framework-json-api/issues/158
    from rest_framework.views import exception_handler as drf_exception_handler

    # Render exception with DRF
    response = drf_exception_handler(exc, context)
    if not response:
        return response

    # Use regular DRF format if not rendered by DRF JSON API and not uniform
    is_json_api_view = rendered_with_json_api(context['view'])
    is_uniform = json_api_settings.UNIFORM_EXCEPTIONS
    if not is_json_api_view and not is_uniform:
        return response

    # Convert to DRF JSON API error format
    response = utils.format_drf_errors(response, context, exc)

    # Add top-level 'errors' object when not rendered by DRF JSON API
    if not is_json_api_view:
        response.data = utils.format_errors(response.data)

    return response 
Example #27
Source File: exceptions.py    From lego with MIT License 5 votes vote down vote up
def exception_handler(exc, context):
    """
    Return special responses on exceptions not supported by drf.
    """
    response = drf_exception_handler(exc, context)

    # Check for IntegrityError, use a custom status code for this.
    if not response and isinstance(exc, IntegrityError):
        set_rollback()
        response = Response(
            {"detail": "Some values are supposed to be unique but are not."},
            status=status.HTTP_409_CONFLICT,
        )

    if response:
        detail = None
        if isinstance(response.data, dict):
            detail = response.data.get("detail")

        log.warn(
            "request_error", status_code=response.status_code, detail=detail, exc=exc
        )
    else:
        log.error("unhandled_request_exception", exc=exc)

    return response 
Example #28
Source File: api.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def exception_handler(exception, context):
    """
    Overwriting Django Rest Frameworks exception handler to provide more
    meaningful exception messages for 404 and validation errors.
    """
    exception = set_exception(exception,
                              context['request'].build_absolute_uri())
    response = drf_exception_handler(exception, context)

    if response:
        response.data = eval_json(response.data)

        return response 
Example #29
Source File: utils.py    From InvenTree with MIT License 5 votes vote down vote up
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 
Example #30
Source File: exception_handlers.py    From desec-stack with MIT License 4 votes vote down vote up
def exception_handler(exc, context):
    """
    desecapi specific exception handling. If no special treatment is applied,
    we default to restframework's exception handling. See also
    https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling
    """

    def _perform_handling(name):
        logger = logging.getLogger('django.request')
        logger.error('{} Supplementary Information'.format(name),
                     exc_info=exc, stack_info=False)

        # Gracefully let clients know that we cannot connect to the database
        response =  Response({'detail': 'Please try again later.'},
                        status=status.HTTP_503_SERVICE_UNAVAILABLE)
        metrics.get('desecapi_database_unavailable').inc()
        return response

    # Catch DB exception and log an extra error for additional context
    if isinstance(exc, OperationalError):
        if isinstance(exc.args, (list, dict, tuple)) and exc.args and \
            exc.args[0] in (
                2002,  # Connection refused (Socket)
                2003,  # Connection refused (TCP)
                2005,  # Unresolved host name
                2007,  # Server protocol mismatch
                2009,  # Wrong host info
                2026,  # SSL connection error
        ):
            return _perform_handling('OperationalError')

    # OSError happens on system-related errors, like full disk or getaddrinfo() failure.
    # Catch it and log an extra error for additional context.
    if isinstance(exc, OSError):
        return _perform_handling('OSError')

    if isinstance(exc, UnsupportedRule):
        return _perform_handling('UnsupportedRule')

    if isinstance(exc, PDNSException):
        return _perform_handling('PDNSException')

    return drf_exception_handler(exc, context)