コード例 #1
0
def op_exception_handler(ex, context):
    """
    统一异常拦截处理
    目的:(1)取消所有的500异常响应,统一响应为标准错误返回
        (2)准确显示错误信息
    :param ex:
    :param context:
    :return:
    """
    msg = ''
    code = '201'

    if isinstance(ex, AuthenticationFailed):
        code = 401
        msg = ex.detail
    elif isinstance(ex, DRFAPIException):
        set_rollback()
        msg = ex.detail
    elif isinstance(ex, exceptions.APIException):
        set_rollback()
        msg = ex.detail
    elif isinstance(ex, Exception):
        logger.error(traceback.format_exc())
        msg = str(ex)
    return ErrorResponse(msg=msg, code=code)
コード例 #2
0
def custom_exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.

    By default we handle the REST framework `APIException`, and also
    Django's built-in `Http404` and `PermissionDenied` exceptions.

    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, IntegrityError):
        exc = AlreadyExistError()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, "auth_header", None):
            headers["WWW-Authenticate"] = exc.auth_header
        if getattr(exc, "wait", None):
            headers["Retry-After"] = "%d" % exc.wait

        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {"error": exc.detail.lower().rstrip(".")}

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)

    return None
コード例 #3
0
def common_exception_handler(exc, context):
    logger.exception('')

    if isinstance(exc, Http404):
        exc = JMSObjectDoesNotExist(object_name=extract_object_name(exc, 1))
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()
    elif isinstance(exc, DJObjectDoesNotExist):
        exc = JMSObjectDoesNotExist(object_name=extract_object_name(exc, 0))
    elif isinstance(exc, ProtectedError):
        exc = ReferencedByOthers()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, str) and isinstance(exc.get_codes(), str):
            data = {'detail': exc.detail, 'code': exc.get_codes()}
        else:
            data = exc.detail

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)
    else:
        unexpected_exception_logger.exception('')

    return None
コード例 #4
0
def exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.

    By default we handle the REST framework `APIException`, and also
    Django's built-in `Http404` and `PermissionDenied` exceptions.

    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    exc = _convert_exception(exc)
    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        # Original implementation:
        #
        # if isinstance(exc.detail, (list, dict)):
        #     data = exc.detail
        # else:
        #     data = {'detail': exc.detail}
        #
        data = _make_response_data(exc)

        views.set_rollback()
        return Response(data, status=exc.status_code, headers=headers)

    return None
コード例 #5
0
def custom_exception_handler(exc, context):
    # give more context on the error since DRF masks it as Not Found
    print(exc)  # todo debug
    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
    print(response)
    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, (DryccException, HealthcheckException)):
        logging.exception(exc.__cause__, exc_info=exc)

    return response
コード例 #6
0
ファイル: exceptions.py プロジェクト: turnhq/turn_profile
def generic_exception_handler(exc, context):
    """
    manage all uncatch exceptions

    Parameters
    ----------
    exc: Exception
    contex: object

    Notes
    -----
    the generic exceptions can handle are:
        * :class:`~Http_error`
        * :class:`~Http_not_found`
        * :class:`~Http_internal_server_error`
        * :class:`~Http_bad_request`

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

    if isinstance(exc, Http_error):
        response = Response(exc.context, status=exc.status_code)
        set_rollback()

    return response
コード例 #7
0
ファイル: exceptions.py プロジェクト: cualbondi/web
def exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.
    By default we handle the REST framework `APIException`, and also
    Django's built-in `Http404` and `PermissionDenied` exceptions.
    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        data = default_exception_renderer(exc, True)

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)

    traceback.print_exc()

    if 'text/html' in context['request'].headers.get('Accept', ''):
        return None
    else:
        data = default_exception_renderer(exc, False)
        return Response(data, status=500)
コード例 #8
0
def exception_handler(exc, context):
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, (list, dict)):
            if isinstance(exc.detail, list):
                errors = exc.detail
            else:
                errors = {k: v[0] for k, v in exc.detail.items()}
        else:
            errors = exc.detail

        set_rollback()
        return Response(
            {
                'code': 0,
                'message': 'failure',
                'errors': errors,
                'data': []
            },
            status=exc.status_code,
            headers=headers)

    return None
コード例 #9
0
def exception_handler(exc: BaseException,
                      context: Optional[Dict] = None) -> Optional[Response]:

    # Special handling for Django base exceptions first
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()
    elif isinstance(exc, ProtectedError):
        exc = ProtectedObjectException(
            "",
            protected_objects=exc.protected_objects,
        )

    if (getattr(settings, "DEBUG", False) and not api_settings.ENABLE_IN_DEBUG
            and not isinstance(exc, exceptions.APIException)):
        # By default don't handle non-DRF errors in DEBUG mode, i.e. Django will treat
        # unhandled exceptions regularly (very evident yellow error page)
        return None

    exception_code, exception_key = _get_main_exception_and_code(exc)

    api_settings.EXCEPTION_REPORTING(exc, context)

    set_rollback()

    return Response(
        dict(
            type=_get_error_type(exc),
            code=exception_code,
            detail=_get_detail(exc, exception_key),
            attr=_get_attr(exc, exception_key),
        ),
        status=_get_http_status(exc),
    )
コード例 #10
0
def exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.

    By default we handle the REST framework `APIException`, and also
    Django's built-in `Http404` and `PermissionDenied` exceptions.

    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    if isinstance(exc, exceptions.S3Error):
        set_rollback()
        return Response(exc.err_data(), status=exc.status_code)

    if isinstance(exc, Http404):
        exc = exceptions.S3NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.S3AccessDenied()
    elif isinstance(exc, (NotAuthenticated, AuthenticationFailed)):
        exc = exceptions.S3AccessDenied()
    elif isinstance(exc, APIException):
        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'detail': exc.detail}

        exc = exceptions.S3Error(message=str(data), status_code=exc.status_code, code=exc.default_code)
    else:
        return None

    set_rollback()
    return Response(exc.err_data(), status=exc.status_code)
コード例 #11
0
def custom_exception_handler(exc: Exception, context):
    # The context argument is not used by the default handler, but can be useful if the exception handler needs
    # further information such as the view currently being handled, which can be accessed as context['view'].

    if isinstance(exc, NotFoundError) or isinstance(exc, Http404):
        exc = NotFoundException()
    elif isinstance(exc, exceptions.PermissionDenied):
        exc = PermissionDeniedException()
    elif isinstance(exc, exceptions.NotAuthenticated):
        exc = NotAuthenticatedException()
    elif isinstance(exc, exceptions.ValidationError):
        exc = BadRequestException(detail=exc.detail)

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if hasattr(exc, 'auth_header'):
            headers['WWW-Authenticate'] = getattr(exc, 'auth_header')
        if hasattr(exc, 'wait'):
            headers['Retry-After'] = '%d' % getattr(exc, 'wait')

        if isinstance(exc.detail, (list, dict)):
            data = {
                'message': Messages.MSG_ONE_OR_MORE_ERRORS_OCCURRED,
                'errors': exc.detail
            }
        else:
            data = {'message': exc.detail}

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)

    return None
コード例 #12
0
def generic_exception_handler(exc, context):
    """
    maneja las excepciones genericas del api

    Parameters
    ----------
    exc: Exception
    contex: object

    Notes
    -----
    las exceptciones genericas pueden ser
        * :class:`~Http_error`
        * :class:`~Http_not_found`
        * :class:`~Http_internal_server_error`
        * :class:`~Http_bad_request`

    tambien soporta las excepciones por default de django
    """
    response = exception_handler(exc, context)

    if isinstance(exc, Http_error):
        response = Response(exc.context, status=exc.status_code)
        set_rollback()

    if response is None and exc:
        response = Response({"detail": "Unhandled error."},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        logger.exception("unhandled error", exc_info=exc)
    return response
def exception_handler(exc, context):

    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.APIException):
        data = {'status_code': exc.status_code, 'errors': {}}
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, list):
            data['errors']['non_field_errors'] = exc.detail
        elif isinstance(exc.detail, dict):
            data['errors'] = exc.detail
        else:
            data['errors']['non_field_errors'] = [exc.detail]

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)
    elif PRETTY_STANDARD_PYTHON_EXCEPTIONS:
        data = {'status_code': 500, 'errors': {}}
        data['errors']['non_field_errors'] = [f'{exc.__class__.__name__}: {exc}']
        return Response(data, status=500)
    return None
コード例 #14
0
def custom_exception_handler(exc, context):  # pylint: disable=too-many-branches
    """ "
    自定义异常返回结果
    DRF内置的异常捕获handler可以处理绝大多数Exception,
    但是无法处理数据库查询等其他错误,此类其他错误都会返回None,
    此时会根据settings.DEBUG来展示对应的500页面
    """
    response = exception_handler(exc, context)
    request_data = context["request"].data

    if response is not None:
        response.data = {
            "errors": [
                {"details": ExceptionHandler.handle(exc), "object": request_data},
            ],
        }
        logger.warning("error response detail:\n%s", response.data)
        return response

    # 未捕获到的其他异常均当做500来处理,尝试包装request_id告知用户
    if settings.ENV_FLAG in ("local", "test"):
        return None

    sentry_sdk.capture_exception(exc)
    details = "服务器错误, 请联系管理员。"
    set_rollback()
    return JsonResponse(
        data={
            "errors": [{"details": details, "object": request_data}],
        },
        status=500,
        json_dumps_params={"ensure_ascii": False},
    )
コード例 #15
0
def custom_exception_handler(exc, context):

    # Log the exception
    if exc is not OSError and exc is not NotAuthenticated:
        is_development = os.getenv("DEVELOPMENT", False)
        if is_development:
            logger.error(exc)
        else:
            capture_exception(exc)

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

    # response == None is an exception not handled by the DRF framework in the call above
    if response is None:
        if isinstance(exc, IntegrityError):
            response = Response({"detail": "Database conflict"},
                                status=status.HTTP_409_CONFLICT)
        else:
            response = Response({'detail': 'Internal server error'},
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        set_rollback()

    return response
コード例 #16
0
def custom_exception_handler(exc, context):
    logger.error('请求出错:{}'.format(exc), exc_info=True)
    error_message = ""
    # 事务回滚
    set_rollback()
    if hasattr(exc, "detail"):
        detail = exc.detail
        if isinstance(detail, list):
            for key, values in exc.detail.items():
                error_message += str(values[0])
        else:
            error_message = detail
    # 处理404 错误
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait
        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'detail': exc.detail}
        response = Response(data, status=exc.status_code, headers=headers)
    elif isinstance(exc, exceptions.APIException):
        response = BaseResponseData.error(422, error_message)
    elif isinstance(exc, ValidationError):
        response = BaseResponseData.error(422, error_message)
    elif isinstance(exc, PermissionDenied):
        response = BaseResponseData.error(403)
    else:
        response = BaseResponseData.error(500)
    return response
コード例 #17
0
def rest_exception_handler(exc, context):
    """
    Rest exception handler
    """
    if isinstance(exc, Http404):
        return ApiNotFoundResponse()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()
    elif isinstance(exc, exceptions.AuthenticationFailed):
        return AuthenticationFailedResponse(exc.detail)
    elif isinstance(exc, exceptions.NotAuthenticated):
        return AuthenticationFailedResponse(exc.detail)
    elif isinstance(exc, AuthenticationExpired):
        return ApiErrorResponse(exc.detail, exc.api_code)
    elif isinstance(exc, UserDisabled):
        return ApiErrorResponse(exc.detail, exc.api_code)
    elif isinstance(exc, SerializerFieldError):
        return ApiDetailErrorResponse(exc.detail, fields=[exc.field])

    if isinstance(exc, exceptions.APIException):
        if isinstance(exc.detail, list):
            data = exc.detail
        elif isinstance(exc.detail, dict):
            data = []
            for key, msg in exc.detail.items():
                data.append("%s %s" % (key, msg))
        else:
            data = exc.detail

        set_rollback()
        return ApiErrorResponse(data)

    return None
コード例 #18
0
def _exception_handler(exc, debug=True):
    """Extract informations that can be sent to the client."""
    status_code = getattr(exc[0], 'status_code', None)
    if status_code:
        detail = (six.text_type(exc[0].detail)
                  if hasattr(exc[0], 'detail') else six.text_type(exc))
        r = dict(status_code=status_code, detail=UNDEFINED_EXCEPTION_MSG)
        # log.warn("Defined error: %s" % r['detail'])
        r['debuginfo'] = detail
        return Response(r)
    else:
        detail = six.text_type(exc)
        excinfo = sys.exc_info()
        debuginfo = "\n".join(traceback.format_exception(*excinfo))

        log.error('Undefined error: "%s". detail: \n%s' % (detail, debuginfo))
        # TODO:待开发,异步发送邮件
        # send_mail(detail, debuginfo, settings.DEFAULT_FROM_EMAIL,
        #           ['*****@*****.**'])
        r = dict(status_code=UNDEFINED_EXCEPTION_CODE,
                 detail=six.text_type(UNDEFINED_EXCEPTION_MSG))
        if debug:
            r['debuginfo'] = detail
        else:
            r['debuginfo'] = None
        set_rollback()
        return Response(r, status=UNDEFINED_EXCEPTION_CODE)
コード例 #19
0
def drf_custom_exception_handler(exc, context):
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        data = {
            "data": {},
            "errors": []
        }

        if isinstance(exc.detail, (dict,)):
            data['errors'] = exc.detail
        else:
            data['errors'] = {'msg': exc.detail}

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)

    return None
コード例 #20
0
def custom_rest_exception_handler(exc, context):
    """ Custom rest api exception handler """
    from rest_framework import exceptions
    from rest_framework.views import exception_handler, set_rollback
    response = exception_handler(exc, context)
    if response is None:
        if isinstance(exc, RequestDataTooBig):
            response = Response({'reason': 'too big data or file upload'},
                                status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)
        else:
            response = Response({'reason': 'unexpected server error'},
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
            traceback.print_exc()
        return response

    err_msg = str(exc)
    if isinstance(exc, ProtectedError):
        data = {'reason': 'cannot delete this record! this record is related to other entities and is protected'}
        set_rollback()
        return Response(data, status=status.HTTP_412_PRECONDITION_FAILED)
    if isinstance(exc, IntegrityError) and ('already exists' in err_msg or 'must make a unique set' in err_msg or
                                            'must be unique' in err_msg):
        data = {'reason': 'duplicate unique key'}
        set_rollback()
        return Response(data, status=status.HTTP_409_CONFLICT)
    if isinstance(exc, exceptions.NotAuthenticated):
        response.status_code = status.HTTP_401_UNAUTHORIZED
    elif isinstance(exc, exceptions.ValidationError) and (
            'already exists' in err_msg or 'must make a unique set' in err_msg or 'must be unique' in err_msg):
        response.status_code = status.HTTP_409_CONFLICT

    return response
コード例 #21
0
ファイル: exception.py プロジェクト: soerjadi/django-skeleton
def exception_handler(exc, context):
    """
        Returns the response that should be used for any given exception.

        By default we handle the REST framework `APIException`, and also
        Django's built-in `Http404` and `PermissionDenied` exceptions.

        Any unhandled exceptions may return `None`, which will cause a 500 error
        to be raised.
        """
    if isinstance(exc, NotFoundException):
        exc = exceptions.NotFound()
    elif isinstance(exc, UnauthorizedException):
        exc = exceptions.PermissionDenied()
    elif isinstance(exc, exceptions.NotAuthenticated):
        exc = NotAuthenticated()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'detail': exc.detail}

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)

    return None
コード例 #22
0
def normalize_exception(exc, context):
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, dict):
            data = exc.get_full_details()
        else:
            d = exc.get_full_details()
            if not isinstance(d, list):
                d = [d]
            data = {_non_field_error_key: d}

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)

    return None
コード例 #23
0
ファイル: exc_handlers.py プロジェクト: zwfec/jumpserver
def common_exception_handler(exc, context):
    logger.exception('')

    if isinstance(exc, Http404):
        exc = JMSObjectDoesNotExist(object_name=extract_object_name(exc, 1))
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()
    elif isinstance(exc, DJObjectDoesNotExist):
        exc = JMSObjectDoesNotExist(object_name=extract_object_name(exc, 0))

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'detail': exc.detail}

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)

    return None
コード例 #24
0
ファイル: views.py プロジェクト: olgoncharov/thingsfree
def exception_handler(exc, context):
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'message': exc.detail}

        set_rollback()
        return Response({
            'status': exc.status_code * 1000,
            'body': data
        },
                        status=exc.status_code,
                        headers=headers)

    return Response({
        'status': 500000,
        'body': {
            'message': 'Unknown error.'
        }
    },
                    status=500)
コード例 #25
0
ファイル: handlers.py プロジェクト: showsmall/evcloud
def exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.
    """
    if isinstance(exc, exceptions.Error):
        set_rollback()
        return Response(exc.data(), status=exc.status_code)

    if isinstance(exc, Http404):
        exc = exceptions.NotFoundError()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.AccessDeniedError()
    elif isinstance(exc, (NotAuthenticated, AuthenticationFailed)):
        exc = exceptions.AuthenticationFailedError()
    elif isinstance(exc, APIException):
        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'detail': exc.detail}

        exc = exceptions.Error(msg=str(data), code=exc.status_code)
    else:
        return None

    set_rollback()
    return Response(exc.data(), status=exc.status_code)
コード例 #26
0
def exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.
    By default we handle the REST framework `APIException`, and also
    Django's built-in `Http404` and `PermissionDenied` exceptions.
    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    headers = None
    if isinstance(exc, APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        data = exc.detail
        if type(data) is ErrorDetail:
            data = str(data)
        status_code = exc.status_code
        set_rollback()

    elif isinstance(exc, Http404):
        data = "Not Found"
        status_code = status.HTTP_404_NOT_FOUND
        set_rollback()

    else:
        data = str(exc)
        status_code = status.HTTP_500_INTERNAL_SERVER_ERROR

    return smart_response(data, status_code=status_code, headers=headers)
コード例 #27
0
def op_exception_handler(ex, context):
    """
    统一异常拦截处理
    目的:(1)取消所有的500异常响应,统一响应为标准错误返回
        (2)准确显示错误信息
    :param ex:
    :param context:
    :return:
    """
    msg = ''
    code = '201'
    request = context.get('request')
    request.session['model_name'] = str(get_verbose_name(view=context.get('view')))

    if isinstance(ex, AuthenticationFailed):
        code = 401
        msg = ex.detail
    elif isinstance(ex, DRFAPIException):
        set_rollback()
        msg = ex.detail
    elif isinstance(ex, exceptions.APIException):
        set_rollback()
        msg = ex.detail
    elif isinstance(ex, Exception):
        logger.error(traceback.format_exc())
        msg = str(ex)
    return ErrorResponse(msg=msg, code=code)
コード例 #28
0
ファイル: exceptions.py プロジェクト: vhellem/lego
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
コード例 #29
0
ファイル: handlers.py プロジェクト: mkurnikov/tipsi_tools
def api_exception_handler(exc, context):

    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        error = {}
        error['reason'] = exc.__class__.__name__
        error['status'] = exc.status_code
        error['code'] = exc.default_code
        error['message'] = exc.default_detail
        error['detail'] = exc.get_full_details()

        set_rollback()
        return Response(
            {'error': error},
            status=exc.status_code,
            headers=headers,
        )

    return None
コード例 #30
0
def open_api_exception_handler(exc, context):
    """
    ds app api 异常处理
    {
        "data": {}
        "code": http status code,
        "status": "success",
        "message": "OK"
    }
    """
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.AuthenticationFailed):
        return Response({
            'code': 401,
            'status': "fail",
            'message': 'Please login.'
        })

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        set_rollback()
        return Response({
            'code': exc.status_code,
            'status': "fail",
            'message': exc.detail
        })

    if isinstance(exc, ApiException):
        # supplier app 异常处理
        detail = exc.detail
        return Response({'code': 400, 'status': "fail", 'message': detail})

    if isinstance(exc, DsApiException):
        # ds app api 异常
        detail = exc.detail
        return Response({"code": 500, "status": "fail", "message": detail})

    if isinstance(exc, Exception):
        # 处理异常
        if DEBUG is False:
            content = traceback.format_exc()
            notify_exception_message.delay(content)
            return Response({
                'code': 500,
                'status': "fail",
                'message': 'Server error'
            })
        else:
            raise exc
    return None
コード例 #31
0
ファイル: views.py プロジェクト: rehandalal/normandy
def exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.

    Adds support the DRF default to also handle django.core.exceptions.ValidationError

    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    response = original_exception_handler(exc, context)

    if response:
        return response

    elif isinstance(exc, DjangoValidationError):
        data = {"messages": exc.messages}
        set_rollback()
        return Response(data, status=status.HTTP_400_BAD_REQUEST)

    return None