码迷,mamicode.com
首页 > 其他好文 > 详细

assert False 与 try 结合 在开发中的使用

时间:2020-04-04 20:32:45      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:odi   try   contex   detail   standard   more   first   stand   str   

 

让错误抛出

发现其中的问题

 

 

# coding=utf-8

from rest_framework.views import exception_handler
from rest_framework.exceptions import ErrorDetail
from share.dj_customer.rest_api_exception import CustomerError


def custom_exception_handler(exc, context):
    # Call REST framework‘s default exception handler first,
    # to get the standard error response.
    ....
        if isinstance(old_data, dict):
            if old_data.get(‘detail‘) is not None:
                if isinstance(old_data[‘detail‘], tuple):
                    new_data[‘code‘], new_data[‘message‘] = old_data[‘detail‘][0:2]
                elif isinstance(old_data[‘detail‘], str):
                    new_data[‘message‘] = old_data[‘detail‘]
            else:
                try:
                    # e.g. user_name [ErrorDetail(string=‘Ensure this field has no more than 16 characters.‘, code=‘max_length‘)]
                    msg = ‘‘
                    for serializer_field, v in old_data.items():
                        if isinstance(serializer_field, str) and isinstance(v, list):
                            if isinstance(v[0], ErrorDetail):
                                msg += serializer_field + ‘:‘ + v[0].__str__()
                            else:
                                assert False
                        else:
                            assert False
                    # e.g.
                    # {
                    #     "success": false,
                    #     "code": 1001,
                    #     "message": "参数错误 : user_name:Ensure this field has no more than 16 characters.age:A valid integer is required."
                    # }
                    new_data[‘code‘], new_data[‘message‘] = CustomerError.PARAM_ERROR
                    new_data[‘message‘] += ‘ : ‘ + msg
                except:
                    assert False

  

 

assert False 与 try 结合 在开发中的使用

标签:odi   try   contex   detail   standard   more   first   stand   str   

原文地址:https://www.cnblogs.com/yuanjiangw/p/12633590.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!