我試圖從REST Django框架創建自定義錯誤響應。Django REST自定義錯誤
我已經列入我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響應中的自定義錯誤消息。
感謝,
當然,但是這是否會通過JSON響應爲我提供自定義錯誤。正如我試過這個,但我得到「全球名稱響應」沒有定義「。 – felix001
您需要導入rest_framework Response:'from rest_framework.response import Response'。是的,這段代碼將返回一個帶有你指定結構的JSON響應(在這種情況下,** {'detail':「無效參數」,'args':['arg1','arg2']} **)和您需要的錯誤代碼(** 400 **,請查看[restframework status codes](http://www.django-rest-framework.org/api-guide/status-codes)瞭解更多信息) – argaen