當前位置: 首頁>>代碼示例>>Python>>正文


Python views.exception_handler方法代碼示例

本文整理匯總了Python中rest_framework.views.exception_handler方法的典型用法代碼示例。如果您正苦於以下問題:Python views.exception_handler方法的具體用法?Python views.exception_handler怎麽用?Python views.exception_handler使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在rest_framework.views的用法示例。


在下文中一共展示了views.exception_handler方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: custom_exception_handler

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:deis,項目名稱:controller,代碼行數:24,代碼來源:exceptions.py

示例2: resolwe_exception_handler

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:genialis,項目名稱:resolwe,代碼行數:23,代碼來源:exceptions.py

示例3: core_exception_handler

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:tryolabs,項目名稱:aws-workshop,代碼行數:24,代碼來源:exceptions.py

示例4: custom_exception_handler

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:project-koku,項目名稱:koku,代碼行數:18,代碼來源:exception_handler.py

示例5: custom_exception_handler

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:gnosis,項目名稱:safe-relay-service,代碼行數:26,代碼來源:views.py

示例6: exception_handler

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:OpenAgricultureFoundation,項目名稱:gro-api,代碼行數:21,代碼來源:views.py

示例7: friendly_exception_handler

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:FutureMind,項目名稱:drf-friendly-errors,代碼行數:22,代碼來源:handlers.py

示例8: exception_handler

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:xuchaoa,項目名稱:CTF_AWD_Platform,代碼行數:20,代碼來源:exceptions.py

示例9: drf_exception_handler

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:forcemain,項目名稱:notes,代碼行數:19,代碼來源:__init__.py

示例10: core_exception_handler

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:Monal5031,項目名稱:cruzz,代碼行數:24,代碼來源:exceptions.py

示例11: base_exception_handler

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:aduranil,項目名稱:django-channels-react-multiplayer,代碼行數:19,代碼來源:exceptions.py

示例12: handle_validation_error

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:lavalamp-,項目名稱:ws-backend-community,代碼行數:18,代碼來源:exception.py

示例13: handle_non_field_error

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:lavalamp-,項目名稱:ws-backend-community,代碼行數:18,代碼來源:exception.py

示例14: custom_exception_handler

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:mitodl,項目名稱:micromasters,代碼行數:26,代碼來源:utils.py

示例15: exception_errors_format_handler

# 需要導入模塊: from rest_framework import views [as 別名]
# 或者: from rest_framework.views import exception_handler [as 別名]
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 
開發者ID:HackSoftware,項目名稱:Django-Styleguide,代碼行數:14,代碼來源:utils.py


注:本文中的rest_framework.views.exception_handler方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。