2017-06-01 180 views
0

使用DRF時,不處理Django的ValueError(django.core.exceptions)和IntegrityError(django.db)。DRf,處理未處理的異常

DRF的def exception_handler有異常處理代碼(APIException,HTTP404,PermissionDenied)

下面是Http404

elif isinstance(exc, Http404): 
    msg = _('Not found.') 
    data = {'detail': six.text_type(msg)} 

    set_rollback() 
    return Response(data, status=status.HTTP_404_NOT_FOUND) 

一個代碼,這樣我可以創建自定義的異常處理器

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

    if isinstance(exc, ValidationError) or isinstance(exc, IntegrityError): 
     data = { 
      'errors': str(exc) 
     } 
     set_rollback() # not sure about this line 
     response = Response(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 

    return response 

我不確定代碼中set_rollback()行的用途,也不確定我是否安全使用此代碼即

回答

0

DRF中默認不處理IntegrityErrorValueError的原因是因爲它們需要根據具體情況進行處理。所以編寫一個像你在這裏試圖做的一般的異常處理程序可能不是正確的方法。

例如,一些IntegrityErrors可能可以忽略,但有些類似的情況發生在資金轉移的中間不能。所以更好地嘗試這樣的事情:

def create(self, request): 
    try : 
     return super(MyViewSet, self).create(request) 
    except IntergrityError: 
     # your decision here how to handle it. 
     raise APIException(detail='Custom message')