2016-05-12 37 views
3

DRF新手在這裏。Django Rest Framework:如何初始化和使用自定義異常處理程序?

我想通過自定義異常處理程序處理項目中的所有異常。基本上,我試圖做的是,如果任何序列化器未能驗證數據,我想發送相應的錯誤消息到我的自定義異常處理程序,並相應地重新格式化錯誤。

我已將以下內容添加到settings.py。

# DECLARATIONS FOR REST FRAMEWORK 
REST_FRAMEWORK = { 
    'PAGE_SIZE': 20, 
    'EXCEPTION_HANDLER': 'main.exceptions.base_exception_handler', 

    'DEFAULT_AUTHENTICATION_CLASSES': (
     'rest_framework.authentication.TokenAuthentication', 
     'rest_framework.authentication.SessionAuthentication' 
    ) 
} 

但是,一旦我發送一個無效的參數,任何項目的端點,我仍然得到DRF驗證的默認的錯誤消息。 (例如{u'email':[u'此字段是必需的。']})

在相應的序列化程序的驗證函數中引發的錯誤永遠不會到達我的異常處理程序。

這是我正在處理的Project Tree的圖像。

我錯過了什麼嗎?

預先感謝您。

回答

2

要做到這一點,您的base_exception_handler應該檢查何時引發了一個ValidationError異常,然後修改並返回自定義錯誤響應。

注: 一個串行引發ValidationError異常,如果數據參數無效,則返回400種狀態)

base_exception_handler,我們會檢查是否正在引發異常的類型是ValidationError的然後修改錯誤格式並返回修改後的錯誤響應。

from rest_framework.views import exception_handler 
from rest_framework.exceptions import ValidationError 

def base_exception_handler(exc, context): 
    # Call DRF's default exception handler first, 
    # to get the standard error response. 
    response = exception_handler(exc, context) 

    # check that a ValidationError exception is raised 
    if isinstance(exc, ValidationError): 
     # here prepare the 'custom_error_response' and 
     # set the custom response data on response object 
     response.data = custom_error_response 

    return response 
相關問題