2017-06-01 182 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')