DRF:自定义来自API的异常消息 [英] DRF: Customising Exception Messages from the API
问题描述
最近我将开始深入研究DRF,我想知道我想开始自定义错误消息,该消息通过API返回以获取不正确的权限,我想包装一些额外的细节
I'm starting to dive into DRF a little deeper of late, and I was wondering I would like to start customising the error messaging that gets return via the API for incorrect permissions, I'd like to wrap a little extra detail.
例如,如果未为受权限限制的端点提供身份验证凭据,则API返回:
For example, if authentication credentials were not provided for an endpoint that is permission restricted, the API returns:
{
"detail": "Authentication credentials were not provided."
}
来自rest_framework.exceptions
的第171行:
Which comes from line 171 from the rest_framework.exceptions
: https://github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py. Really, I'd like this to be consistent with the
{
"success": false,
"message": "Authentication credentials were not provided.",
"data": null
}
所以,我认为我现在需要开始自定义自己的异常.
So, I assume I now need to begin customising my own exceptions.
我应该如何最好地做到这一点?
How best should I go about doing this?
也许它与序列化程序内的default_error_messages = {}
有联系...
Perhaps it has some tie in with default_error_messages = {}
inside the serializer ...
推荐答案
您可以在settings.py
上覆盖DRF的默认异常处理程序和JSON解析器:
You can override DRF's default exception handler and JSON parser on your settings.py
:
REST_FRAMEWORK = {
...
'EXCEPTION_HANDLER': 'helpers.exceptions.custom_exception_handler',
'DEFAULT_RENDERER_CLASSES': [
'helpers.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
]
}
然后只需自定义如何处理异常以及如何呈现响应:
And then it's just a matter of customizing how to handle your exceptions and how to render the responses:
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":
And you can use the custom JSON renderer in case you need to do any extra formatting on the response, in my case I had to add a "status_code" to the payload:
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)
只是将成功状态代码合并到数据中的一种简单方法.
My Errors.success(response.data)
was just a simpler way to merge the success status code to the data.
这篇关于DRF:自定义来自API的异常消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!