2017-06-01 9 views
0

DRFを使用する場合、DjangoのValueError(django.core.exceptions)とIntegrityError(django.db)は処理されません。DRf、未処理例外を処理します

DRFのdef exception_handlerがために例外処理コードを持っている(にApiException、Http404、PermissionDenied)

以下

は、だから私は

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 
としての私のカスタム例外ハンドラを作成することができます 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) 

のコードです

私はコードのset_rollback()行の目的についてはわかりませんが、私はこのタラで安全だとは分かりませんe。

答えて

0

IntegrityErrorValueErrorがデフォルトでDRFで処理されない理由は、ケースバイケースで処理する必要があるためです。だからここでやろうとしているような一般的な例外ハンドラを書くのは正しい方法ではないでしょう。

例えば、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')