【发布时间】: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