Django-REST-framework自定义异常返回信息

我们如果使用了DRF对于异常捕捉的范围是有限的。我们先看下Django中配置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def exception_handler(exc, context):
"""
Returns the response that should be used for any given exception.

By default we handle the REST framework `APIException`, and also
Django's built-in `Http404` and `PermissionDenied` exceptions.

Any unhandled exceptions may return `None`, which will cause a 500 error
to be raised.
"""
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

if isinstance(exc.detail, (list, dict)):
data = exc.detail
else:
data = {'detail': exc.detail}

set_rollback()
return Response(data, status=exc.status_code, headers=headers)

elif isinstance(exc, Http404):
msg = _('Not found.')
data = {'detail': six.text_type(msg)}

set_rollback()
return Response(data, status=status.HTTP_404_NOT_FOUND)

elif isinstance(exc, PermissionDenied):
msg = _('Permission denied.')
data = {'detail': six.text_type(msg)}

set_rollback()
return Response(data, status=status.HTTP_403_FORBIDDEN)

# Note: Unhandled exceptions will raise a 500 error.
return None

我们看到了只对部分异常进行了捕捉,我们想返回一些定制的信息很难实现。

现在我们自定义一个自己的异常

然后在custom_exception_handler中进行异常类型判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from rest_framework.views import exception_handler

class DataException(Exception):

def __init__(self, code=0, status=status.HTTP_400_BAD_REQUEST, data=None, message=""):

self.code = code
self.status = status
self.message = message
self.data = data

def __str__(self):
return self.message

def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.

if isinstance(exc, DataException):
return Response(data=exc.data, status=exc.status, message=exc.message)

response = exception_handler(exc, context)
# 其他逻辑代码
return response

我们还需要将上述代码配置到settings.py文件。

1
2
3
4
# 认证配置
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'exception_handler.custom_exception_handler',
}

完成以上配置 我们就可以进行自定义异常信息返回拉!

1
raise DataException(message="自定义信息")

这个个人觉得比较实用,对于不同接口需要提示不同信息,我们完全可以这么设置。

参考文章:

http://drf.jiuyou.info/#/drf/exceptions

https://my.oschina.net/duoduo3369/blog/612733

知识就是财富
如果您觉得文章对您有帮助, 欢迎请我喝杯水!