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