【问题标题】:customize error message in django rest在 django rest 中自定义错误消息
【发布时间】:2014-07-14 08:36:34
【问题描述】:

我想自定义来自 django rest 框架的错误响应。 这是来自 django rest 的诽谤错误响应..

{
    "style": [
        "This field is required."
    ], 
    "code": [
        "code must be in 60 to 120 chars."
    ]
}  

我想自定义它......

{
    "style": [
        "error_code":"20"
        "error_message":"This field is required."
    ], 
    "code": [
        "error_code":"22"
        "error_message":"code must be in 60 to 120 chars."
    ]
}  

【问题讨论】:

标签: python django rest django-rest-framework


【解决方案1】:

我在显示错误时遇到了同样的问题。首先你应该知道你不能在列表中使用键值对(即"style": ["error_code": "20", "error_message": "This field is required."]),如果你想将你的错误转换为这个自定义类型,你应该将你的类型更改为字典。一种简单的方法是您可以拥有自己的自定义异常处理程序,然后告诉 rest 框架使用该异常处理程序来自定义您的异常。首先你应该在你的项目中添加以下行settings.py:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'utils.exception_handlers.custom_exception_handler', # You should add the path to your custom exception handler here.
}

这表明所有的异常都应该通过这个处理程序。之后,您应该添加 python 文件并在其中添加您的代码(使用前面提到的 settings.py 中的此文件路径)。在以下代码中,您可以看到此处理程序的示例:

from rest_framework.exceptions import ErrorDetail
from rest_framework.views import exception_handler
    
def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)
    custom_data = {}

    if isinstance(response.data, dict):
        for key, value in response.data.items():
            if value and isinstance(value, list) and isinstance(value[0], ErrorDetail):
                custom_response[key] = {
                    "error_message": str(value[0]),
                    "error_code": response.status_code # or any custom code that you need
                }
            else:
                break

    if custom_data:
        response.data = custom_data
    return response

注意:这是一个简单的示例,您应该测试您的 API 以确保一切正常。

【讨论】:

    猜你喜欢
    • 2015-08-03
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 2015-01-12
    • 2017-11-29
    • 1970-01-01
    • 2014-05-11
    • 2017-11-01
    相关资源
    最近更新 更多