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