django DRF在自定义异常处理程序错误消息中显示详细消息

fquxozlt  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(156)

下面是我的自定义异常处理程序:

def my_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response is not None:
        error_code = 'unknown'                
        if hasattr(exc, 'default_code') :
            error_code = exc.default_code

        message = ''
        if hasattr(exc, 'default_detail'):
            message = exc.default_detail
                   
        error = {
            "error":response.data,
            "code":error_code,
            'message':message,
        }
        response.data = error

    return response

这里的问题是,每当我发送错误数据时,都会得到如下响应:

{
    "error": {
        "email": [
            "Enter a valid email address."
        ],
        "phone_number": [
            "asd is not a valid phone"
        ]
    },
    "code": "invalid",
    "message": "Invalid input."
}

正如你所看到的,消息只是“无效的输入”。但是我想在这里得到一个详细的消息。关于它有什么想法吗?

q35jwt9p

q35jwt9p1#

试试这个,也许你会得到它。

from django.http import JsonResponse
from rest_framework.views import exception_handler


def get_response(message="", result={}, status=False, status_code=200):
    return {
        "message": message,
        "result": result,
        "status": status,
        "status_code": status_code,
    }



def get_error_message(error_dict):
field = next(iter(error_dict))
response = error_dict[next(iter(error_dict))]
if isinstance(response, dict):
    response = get_error_message(response)
elif isinstance(response, list):
    response_message = response[0]
    if isinstance(response_message, dict):
        response = get_error_message(response_message)
    else:
        response = field + ": " + response[0]
return response

def handle_exception(exc, context):
    error_response = exception_handler(exc, context)
    if error_response is not None:
        error = error_response.data

        if isinstance(error, list) and error:
            if isinstance(error[0], dict):
                error_response.data = get_response(
                    message=get_error_message(error),
                    status_code=error_response.status_code,
                )

            elif isinstance(error[0], str):
                error_response.data = get_response(
                    message=error[0],
                    status_code=error_response.status_code
                )

        if isinstance(error, dict):
            error_response.data = get_response(
                message=get_error_message(error),
                status_code=error_response.status_code
            )
    return error_response


class ExceptionMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        response = self.get_response(request)

        if response.status_code == 500:
            response = get_response(
                message="Internal server error, please try again later",
                status_code=response.status_code
            )
            return JsonResponse(response, status=response['status_code'])

        if response.status_code == 404 and "Page not found" in str(response.content):
            response = get_response(
                message="Page not found, Something went wrong.",
                status_code=response.status_code
            )
            return JsonResponse(response, status=response['status_code'])

        if response.status_code == 401:
            response = get_response(
                message=response.data['message'],
                status_code=response.status_code
            )
            return JsonResponse(response, status=response['status_code'])

        return response

相关问题