在Django中面临异常时发送自定义错误消息

时间:2020-03-31 12:59:33

标签: python django

我正在尝试为客户端获取正确的错误消息。目前,错误处理是这种方式。

    except Exception as error:
        return Response(
            {'errors': str(error)
             },
            status=status.HTTP_400_BAD_REQUEST,
        )

我们只是将错误转换为str并发送,但这给客户端带来了麻烦。这是我的回应。

{
    "errors": "{'total_employees': [ErrorDetail(string='Ensure this value is less than or equal to 2147483647.', code='max_value')], 'contact_phone_number': [ErrorDetail(string='Phone number must be entered in the correct format .', code='invalid'), ErrorDetail(string='Ensure this field has no more than 12 characters.', code='max_length')]}"
}

我们如何将错误转换为正确格式的消息。

0 个答案:

没有答案