我在显示错误时遇到了同样的问题。首先你应该知道你不能在列表中使用键值对(即"style": ["error_code": "20", "error_message": "This field is required."]),如果你想将你的错误转换为这个自定义类型,你应该将你的类型更改为字典。一种简单的方法是您可以拥有自己的自定义异常处理程序,然后告诉 rest 框架使用该异常处理程序来自定义您的异常。首先你应该在你的项目中添加以下行settings.py:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'utils.exception_handlers.custom_exception_handler', # You should add the path to your custom exception handler here.
}
这表明所有的异常都应该通过这个处理程序。之后,您应该添加 python 文件并在其中添加您的代码(使用前面提到的 settings.py 中的此文件路径)。在以下代码中,您可以看到此处理程序的示例:
from rest_framework.exceptions import ErrorDetail
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.
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
custom_data = {}
if isinstance(response.data, dict):
for key, value in response.data.items():
if value and isinstance(value, list) and isinstance(value[0], ErrorDetail):
custom_response[key] = {
"error_message": str(value[0]),
"error_code": response.status_code # or any custom code that you need
}
else:
break
if custom_data:
response.data = custom_data
return response
注意:这是一个简单的示例,您应该测试您的 API 以确保一切正常。