DRF默认的异常处理流程如下:
rest_framework.views.exception_handler
函数来处理异常。APIException
类)和Django内置的Http404、PermissionDenied
异常,提取错误信息并返回响应下面是DRF的exception_handler
异常处理函数源码
# rest_framework.views.py
def exception_handler(exc, context):
if isinstance(exc, Http404):
exc = exceptions.NotFound(*(exc.args))
elif isinstance(exc, PermissionDenied):
exc = exceptions.PermissionDenied(*(exc.args))
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)
return None
DRF 自定义异常处理流程示例:
custom_exception_handler
函数,作为DRF的全局异常处理器ValidationError
或 Django 的验证错误,调用对应处理函数提取错误信息在 settings.py
中,配置DRF自定义异常处理函数,作为全局异常处理器。
REST_FRAMEWORK = {
# ...
# 全局异常处理
"EXCEPTION_HANDLER": "mars_framework.exceptions.base.custom_exception_handler",
# ...
}
您正在阅读的是《Django从入门到实战》专栏!关注不迷路~
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。