我想在引发 HTTP 400 错误时返回自定义错误。
这是我的模型:
class User(models.Model):
fullname = models.CharField(max_length=100)
phone = models.CharField(max_length=50, unique=True)
password = models.CharField(max_length=50, default='SOME STRING')
这是我的序列化器类:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'fullname', 'phone', 'password')
这是我在 View 类中的类:
class RegisterUsers(generics.CreateAPIView):
.
.
.
serializer = UserSerializer(data={
"fullname": fullname,
"phone": phone,
"password": password
}
)
if not serializer.is_valid(raise_exception=True):
return
如果我尝试使用相同的号码注册两次,则会出现 400 bad request 错误,如下面的屏幕截图所示:
我想捕获错误并将其解析为如下所示的自定义响应:
谁能帮我解决这个问题吗? 提前致谢。
最佳答案
您可以重写 DRF 自定义异常处理程序方法:
from rest_framework.views import exception_handler
from rest_framework.exceptions import ValidationError
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):
# This is where you would prepare the 'custom_error_response'
# and set the custom response data on response object
response.data = custom_error_response
return response
要启用自定义处理程序,请在设置文件中添加 EXCEPTION_HANDLER
设置:
REST_FRAMEWORK = {
'PAGE_SIZE': 20,
'EXCEPTION_HANDLER': 'path.to.your.module.base_exception_handler',
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication'
)
}
关于django - 使用 django 和 django Rest 框架在 Rest API 中引发自定义 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52780307/