【发布时间】: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