django rest_framework自定义异常错误

问题描述 投票:0回答:1

我是django休息框架的新手,并试图在django中创建自定义的错误响应!

Django Rest Framework Exceptions

经过这一切,似乎都很简单,但当我尝试添加自定义异常时导入错误。

settings.朋友

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'project.restapi.utils.custom_exception_handler'
}

ImportError异常值: 无法为API设置'EXCEPTION_HANDLER'导入'project.restapi.utils.custom_exception_handler'。 AttributeError:模块'project.restapi.utils'没有属性'custom_exception_handler'

custom_exception_handler.朋友

from rest_framework.views import exception_handler

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

model.朋友

class Users(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def retrieve(self, request, *args, **kwargs):
        # call the original 'list' to get the original response
        response = super(Users, self).retrieve(request, *args, **kwargs) 

        response.data = {"collection": {"data": response.data},"statusCode":response.status_code,"version":"1.0"}
        # customize the response data
        if response is not None:
            return response
        else:
            # return response with this custom representation
            response.data = {"collection": {"data": response.data},"statusCode":response.status_code,"version":"1.0","error":response.exception}
            return response

所以在上面的模型工作正常,除非我尝试击中不在数据库中的用户应该引发错误 - 未找到,所以我试图自定义未发现对我自己有意义。而已

我试图解决,但很难这样做!!,

Django版本:2.1.5 Python - 3.7.0

python django django-rest-framework
1个回答
1
投票

由于你的custom_exception_handler位于一个名为custom_exception_handler.py的文件中。您可以尝试将EXCEPTION_HANDLER设置更改为:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'project.restapi.utils.custom_exception_handler.custom_exception_handler'
}
© www.soinside.com 2019 - 2024. All rights reserved.