customize error message in django rest

时光总嘲笑我的痴心妄想 提交于 2021-02-19 07:31:17

问题


i want to customize the error response from django rest framework. this is slandered error response from django rest..

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

i want to customize it like....

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

回答1:


I had the same problem in showing errors. First of all you should know that you can't use key-value pairs in a list (i.e. "style": ["error_code": "20", "error_message": "This field is required."]) and you should change your type to dictionary if you want to convert your error to this custom type. One easy way is that you can have your own custom exception handler and then tell rest framework to use that exception handler to customize your exceptions. First you should add the following line in your project settings.py:

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

Which tells that all of the exceptions should pass through this handler. After that you should add python file and add your codes in it (use this file path in your settings.py which mentioned before). In following code you can see an example of this handler:

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

Note: This was a quick example and you should test your APIs to make sure that everything works.



来源:https://stackoverflow.com/questions/23855409/customize-error-message-in-django-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!