2020-07-31 10:18:52 +00:00
|
|
|
|
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist as DJObjectDoesNotExist
|
|
|
|
|
from django.http import Http404
|
|
|
|
|
from django.utils.translation import gettext
|
2020-12-17 06:41:55 +00:00
|
|
|
|
from django.db.models.deletion import ProtectedError
|
2020-07-31 10:18:52 +00:00
|
|
|
|
from rest_framework import exceptions
|
|
|
|
|
from rest_framework.views import set_rollback
|
|
|
|
|
from rest_framework.response import Response
|
|
|
|
|
|
2020-12-17 06:41:55 +00:00
|
|
|
|
from common.exceptions import JMSObjectDoesNotExist, ReferencedByOthers
|
2020-10-27 08:32:02 +00:00
|
|
|
|
from logging import getLogger
|
2020-09-27 11:47:13 +00:00
|
|
|
|
|
2020-10-27 08:32:02 +00:00
|
|
|
|
logger = getLogger('drf_exception')
|
|
|
|
|
unexpected_exception_logger = getLogger('unexpected_exception')
|
2020-07-31 10:18:52 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def extract_object_name(exc, index=0):
|
|
|
|
|
"""
|
|
|
|
|
`index` 是从 0 开始数的, 比如:
|
|
|
|
|
`No User matches the given query.`
|
|
|
|
|
提取 `User`,`index=1`
|
|
|
|
|
"""
|
|
|
|
|
(msg, *_) = exc.args
|
|
|
|
|
return gettext(msg.split(sep=' ', maxsplit=index + 1)[index])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def common_exception_handler(exc, context):
|
2020-09-27 11:47:13 +00:00
|
|
|
|
logger.exception('')
|
|
|
|
|
|
2020-07-31 10:18:52 +00:00
|
|
|
|
if isinstance(exc, Http404):
|
|
|
|
|
exc = JMSObjectDoesNotExist(object_name=extract_object_name(exc, 1))
|
|
|
|
|
elif isinstance(exc, PermissionDenied):
|
|
|
|
|
exc = exceptions.PermissionDenied()
|
|
|
|
|
elif isinstance(exc, DJObjectDoesNotExist):
|
|
|
|
|
exc = JMSObjectDoesNotExist(object_name=extract_object_name(exc, 0))
|
2020-12-17 06:41:55 +00:00
|
|
|
|
elif isinstance(exc, ProtectedError):
|
|
|
|
|
exc = ReferencedByOthers()
|
2020-07-31 10:18:52 +00:00
|
|
|
|
|
|
|
|
|
if isinstance(exc, exceptions.APIException):
|
|
|
|
|
headers = {}
|
|
|
|
|
if getattr(exc, 'auth_header', None):
|
|
|
|
|
headers['WWW-Authenticate'] = exc.auth_header
|
|
|
|
|
if getattr(exc, 'wait', None):
|
|
|
|
|
headers['Retry-After'] = '%d' % exc.wait
|
|
|
|
|
|
2020-11-03 09:31:25 +00:00
|
|
|
|
if isinstance(exc.detail, str) and isinstance(exc.get_codes(), str):
|
|
|
|
|
data = {'detail': exc.detail, 'code': exc.get_codes()}
|
2020-07-31 10:18:52 +00:00
|
|
|
|
else:
|
2020-11-03 09:31:25 +00:00
|
|
|
|
data = exc.detail
|
2020-07-31 10:18:52 +00:00
|
|
|
|
|
|
|
|
|
set_rollback()
|
|
|
|
|
return Response(data, status=exc.status_code, headers=headers)
|
2020-10-27 08:32:02 +00:00
|
|
|
|
else:
|
|
|
|
|
unexpected_exception_logger.exception('')
|
2020-07-31 10:18:52 +00:00
|
|
|
|
|
|
|
|
|
return None
|