[英]Django REST Custom Errors
我正在嘗試從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)
從文檔 -
請注意,只會針對由引發的異常生成的響應調用異常處理程序。 它不會用於視圖直接返回的任何響應,例如序列化程序驗證失敗時通用視圖返回的
HTTP_400_BAD_REQUEST
響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.