python – Django REST自定义错误
发布时间:2020-05-23 09:43:44 所属栏目:Python 来源:互联网
导读:我正在尝试从REST Django框架创建自定义错误响应. 我在views.py中包含了以下内容, from rest_framework.views import exception_handlerdef custom_exception_handler(exc): Custom exception handler for Django Rest Framework
|
我正在尝试从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
并且还将以下内容添加到settings.py中. REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',),'EXCEPTION_HANDLER': 'project.input.utils.custom_exception_handler'
}
我错过了什么,因为我没有得到预期的回应.即400 API响应中的自定义错误消息. 谢谢, 解决方法正如Bibhas所说,使用自定义异常处理程序,您只能在调用异常时返回自己定义的错误.如果要在不触发异常的情况下返回自定义响应错误,则需要在视图本身中返回它.例如:return Response({'detail' : "Invalid arguments",'args' : ['arg1','arg2']},status = status.HTTP_400_BAD_REQUEST) (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
