【问题标题】:DRf, handle unhandled exceptionDRf,处理未处理的异常
【发布时间】:2017-06-01 03:24:38
【问题描述】:

使用 DRF 时,Django 的 ValueError (django.core.exceptions) 和 IntegrityError (django.db) 不会被处理。

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() 行的用途,也不确定我是否可以安全地使用此代码。

【问题讨论】:

  • 附注:您可以使用类元组作为isinstance 的第二个参数。 isinstance(exc, (ValidationError, IntegrityError))

标签: django django-rest-framework


【解决方案1】:

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')

【讨论】:

    猜你喜欢
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    相关资源
    最近更新 更多