我正在尝试从REST Django框架创建自定义错误响应.
我在views.py中包含了以下内容,
from rest_framework.views import exception_handler
def custom_exception_handler(exc):
"""
Custom exception handler for Django Rest Framework that adds
the `status_code` to the response and renames the `detail` key to `error`.
"""
response = exception_handler(exc)
if response is not None:
response.data['status_code'] = response.status_code
response.data['error'] = response.data['detail']
response.data['detail'] = "CUSTOM ERROR"
return response
Run Code Online (Sandbox Code Playgroud)
并且还将以下内容添加到settings.py中.
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
'EXCEPTION_HANDLER': 'project.input.utils.custom_exception_handler'
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么,因为我没有得到预期的回应.即400 API响应中的自定义错误消息.
谢谢,
arg*_*aen 11
正如Bibhas所说,使用自定义异常处理程序,您只能在调用异常时返回自己定义的错误.如果要在不触发异常的情况下返回自定义响应错误,则需要在视图本身中返回它.例如:
return Response({'detail' : "Invalid arguments", 'args' : ['arg1', 'arg2']},
status = status.HTTP_400_BAD_REQUEST)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5225 次 |
| 最近记录: |