2014-03-31 69 views
6

我試圖從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響應中的自定義錯誤消息。

感謝,

回答

11

正如Bibhas所說,使用自定義異常處理程序時,只有在調用異常時才能返回自己定義的錯誤。如果您想要返回自定義響應錯誤而不觸發異常,則需要將其返回到視圖本身中。例如:

return Response({'detail' : "Invalid arguments", 'args' : ['arg1', 'arg2']}, 
        status = status.HTTP_400_BAD_REQUEST) 
+0

當然,但是這是否會通過JSON響應爲我提供自定義錯誤。正如我試過這個,但我得到「全球名稱響應」沒有定義「。 – felix001

+3

您需要導入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

0

the documentation -

注意異常處理程序纔會被調用由引發的異常生成的響應。它不會用於視圖直接返回的任何響應,例如在串行器驗證失敗時通用視圖返回的HTTP_400_BAD_REQUEST響應。