您可以覆盖 DRF 的默认异常处理程序和 JSON 解析器settings.py
:
REST_FRAMEWORK = {
...
'EXCEPTION_HANDLER': 'helpers.exceptions.custom_exception_handler',
'DEFAULT_RENDERER_CLASSES': [
'helpers.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
]
}
然后只需自定义如何处理异常以及如何呈现响应即可:
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)
# Customize your exception handling here
return response
如果您需要对响应进行任何额外的格式化,您可以使用自定义 JSON 渲染器,在我的情况下,我必须向有效负载添加“status_code”:
class JSONRenderer(BaseJsonRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Render `data` into JSON, returning a bytestring.
"""
<Base code from the original class...>
response = renderer_context.get('response')
if response and 200 <= response.status_code <= 299 and 'status_code' not in response.data:
response.data = Errors.success(response.data)
<Base code from the original class...>
我Errors.success(response.data)
只是将成功状态代码合并到数据的一种更简单的方法。