【问题标题】:django rest framework custom exception handling doesn't return expected error codedjango rest框架自定义异常处理不返回预期的错误代码
【发布时间】:2018-11-16 11:36:36
【问题描述】:

我正在尝试使用 django rest 框架在项目中实现自定义错误处理,并且我希望它在尝试创建新用户但电子邮件已被使用时返回 json(我正在强制执行电子邮件的唯一性)。我想返回一个错误代码 400 并且生成的 json 是这样的:

{
    "email": [
        "eMAil already in use."
    ]
}

我实现了https://medium.com/@mwhitt.w/restful-error-messages-with-django-537047892dff 中提出的解决方案,但我收到了 500 错误代码并且没有返回 json。

这是我的customexception.py

class BaseCustomException(Exception):
    status_code = None
    error_message = None
    is_an_error_response = True

    def __init__(self, error_message):
        Exception.__init__(self, error_message)
        self.error_message = error_message

    def to_dict(self):
        return {'errorMessage':self.error_message}

class ExistingEmailException(BaseCustomException):
    status_code = 400

    def __init__(self):
        BaseCustomException.__init__(self, 'eMail already in use')

这是我的middleware.py

import traceback
from django.http import JsonResponse

def is_registered(exception):
    try:
        return exception.is_an_error_response
    except AttributeError:
        return False

class RequestExceptionHandler:
    def process_exception(self, request, exception):
        if is_registered(exception):
            status = exception.status_code
            exception_dict = exception.to_dict()
        else:
            status = 500
            exception_dict = {'errorMessage':'Unexpected Error!'}

        error_message = exception_dict['errorMessage']
        traceback.print_exc()
        return JsonResponse(exception_dict, status=status)

这是我的序列化器:

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'first_name', 'last_name', 'email', 'password')

    def create(self, validated_data):
        try:
            user = models.User.objects.get(email=validated_data.get('email'))
        except User.DoesNotExist:
            user = models.User.objects.create(**validated_data)

            user.set_password(user.password)
            user.save()
            Token.objects.create(user=user)

            return user
        else:
            raise ExistingEmailException()

这是我得到的结果:

  File "/Users/hugovillalobos/Documents/Code/IntellibookProject/Intellibook/UsersManagerApp/serializers.py", line 27, in create
    raise ExistingEmailException()
GeneralApp.customexceptions.ExistingEmailException: eMail already in use
[06/Jun/2018 17:12:20] "POST /es/users_manager/users/ HTTP/1.1" 500 102163

感谢您的帮助。

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    我认为您收到意外错误代码的原因是您所遵循的示例不是为与 django-rest-framework 一起使用而设计的。虽然理论上应该可以使用 django 的中间件来劫持响应(我正在查看响应 this SO question 的第一条评论),但最简单且在我看来最好的方法是关注 the DRF manual on custom exceptions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      相关资源
      最近更新 更多