【问题标题】:Prioritizing error messages in Python Dict在 Python Dict 中优先处理错误消息
【发布时间】:2018-10-03 21:28:52
【问题描述】:

我进行 API 调用,如果出现问题,它们会返回错误列表:例如

[
{'field': u'currency', 'message': 'must be USD', 
 'request_pointer': '/customer_bank_accounts/currency'}, 
{'field': 'iban', 'message': 'is invalid', 
'request_pointer': u'/customer_bank_accounts/iban'}]

我想向用户返回一个错误并确定错误的优先级。错误可以按任何顺序出现。

我知道我可以抛出整个列表来寻找第一个错误,例如

for error in errors:
    if error['message'] == 'is invalid' and error['field'] == 'iban'
        return "error message 1"

for error in errors:
    if error['message'] == 'is invalid' and error['field'] == 'country code'
        return "error message 2"

但这是丑陋的代码,需要多次遍历列表。有没有更好的方法?

【问题讨论】:

    标签: python list dictionary error-handling


    【解决方案1】:

    我非常喜欢使用字典进行输入。它们易于存储,提供 O(1) 查找,并确保您的输入与逻辑分离。

    errors = [{'field': u'currency', 'message': 'must be USD', 
               'request_pointer': '/customer_bank_accounts/currency'}, 
              {'field': 'iban', 'message': 'is invalid', 
               'request_pointer': u'/customer_bank_accounts/iban'}]
    
    error_dict = {('is invalid', 'iban'): 'error message 1',
                  ('is invalid', 'country code'): 'error message 2'}
    
    for idx, error in enumerate(errors):
        key = (error['message'], error['field'])
        if key in error_dict:
            print(idx, error_dict[key])
    

    【讨论】:

    • 在这种情况下,我按 error_dict 进行优先级排序,但使用 dicts 无法跟踪错误出现在 dict 中的位置。如果它是一个列表,我可以使用索引来分配优先级。
    • @user7692855,我没有完全掌握。如果字典项的顺序很重要,您可以使用OrderedDict
    【解决方案2】:

    在我看来,您应该像这样创建自己的错误

    class USDException(Exception):
        "Exception Here"
        pass
    

    然后您可以使用属性错误处理技术来传递适当的错误,例如

    try:
      dostuff()
    except Exception as e:
      print(e)
    

    【讨论】:

      【解决方案3】:

      你可以像矩阵一样。

      您使用第一个索引作为消息和第二个作为字段进行构建。你以前构建过。

      构建矩阵:

      code_error['is invalid']['iban'] = 'error message 1'
      ...
      

      使用:

      return code_error[error['message']][error['field']]
      

      我觉得它看起来会更漂亮。它会变得更有条理。

      【讨论】:

        【解决方案4】:

        您可以尝试制作一组​​您关心的 errors 列表中的部分:

        errorset = set([d['field']+' '+d['message'] for d in errors])
        if 'iban is invalid' in errorset:
             return "error message 1"
        elif 'country code is invalid' in errorset:
             return "error message 2"
        

        集合具有恒定的查找时间来检查某物是否是成员,因此您只需在创建更易于阅读的列表并将其添加到集合中时遍历列表。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-09-28
          • 1970-01-01
          • 2021-12-26
          • 1970-01-01
          • 2013-12-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多