问题描述
使用DRF时,不处理Django的ValueError(django.core.exceptions)和IntegrityError(django.db)。
When using DRF, Django's ValueError (django.core.exceptions) and IntegrityError (django.db) is not handled.
DRF的 def exception_handler
具有(APIException,Http404,PermissionDenied)的异常处理代码
DRF's def exception_handler
has exception handling code for (APIException, Http404, PermissionDenied)
下面是 Http404 $的代码c $ c>
elif isinstance(exc, Http404):
msg = _('Not found.')
data = {'detail': six.text_type(msg)}
set_rollback()
return Response(data, status=status.HTTP_404_NOT_FOUND)
所以我可以将自定义异常处理程序创建为
So I can create my custom exception handler as
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()$ c $的目的c>在代码行中输入,并且不确定是否可以安全使用此代码。
I'm not sure about the purpose of set_rollback()
line in the code, and not sure if I'm safe with this code.
推荐答案
<$ c在DRF中,默认情况下不处理$ c> IntegrityError 和 ValueError
是因为它们需要根据具体情况进行处理。因此,编写类似您在此处尝试执行的通用异常处理程序可能不是正确的方法。
The reason that IntegrityError
and ValueError
aren't handled by default in DRF is because they need to be handled in a case by case basis. So writing a generic exception handler like what you are trying to do here probably isn't the right way.
例如,某些 IntegrityErrors
可能只是被忽略,但类似的情况发生在基金中间不能转让。所以最好尝试这样的事情:
For example, some IntegrityErrors
can probably be just ignored, but some like that happens in the middle of a fund transfer cannot be. So better to try something like this:
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')
这篇关于DRf,处理未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!