代码之家  ›  专栏  ›  技术社区  ›  Mat

是否有传播错误和警告详细信息的模式?

  •  6
  • Mat  · 技术社区  · 16 年前

    是否有传播错误和警告详细信息的通用模式?通过 错误 我的意思是严重的问题会导致代码流停止。通过 警告 我指的是值得通知用户问题的问题,但是这些问题太小,无法阻止程序流。

    我目前使用异常来处理硬错误,并使用python日志框架来记录警告。但现在我想在当前正在处理的记录的数据库字段中记录警告。我想,我希望警告以与异常相同的方式冒泡,但不停止程序流。

    >>> import logging
    >>>
    >>> def process_item(item):
    ...     if item:
    ...         if item == 'broken':
    ...             logging.warning('soft error, continue with next item')
    
    ...     else:
    ...         raise Exception('hard error, cannot continue')
    ...
    >>> process_item('good')
    >>> process_item(None)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 6, in process_item
    Exception: hard error, cannot continue
    >>> process_item('broken')
    WARNING:root:soft error, continue with next item
    

    这个例子(以及我当前的问题)是在Python中,但是它也应该应用于其他语言,但也有例外。


    跟随 David 的建议和下面的示例的简短播放,python的 warnings 模块是前进的道路。

    import warnings
    
    class MyWarning(Warning):
        pass
    
    def causes_warnings():
        print 'enter causes_warnings'
        warnings.warn("my warning", MyWarning)
        print 'leave causes_warnings'
    
    def do_stuff():
        print 'enter do_stuff'
        causes_warnings()
        causes_warnings()
        causes_warnings()
        print 'leave do_stuff'
    
    with warnings.catch_warnings(record=True) as w:
        # Cause all warnings to always be triggered.
        warnings.simplefilter("always")
        # Trigger a number of warnings.
        do_stuff()
        # Do something (not very) useful with the warnings generated
        print 'Warnings:',','.join([str(warning.message) for warning in w])
    

    输出:

    enter do_stuff
    enter causes_warnings
    leave causes_warnings
    enter causes_warnings
    leave causes_warnings
    enter causes_warnings
    leave causes_warnings
    leave do_stuff
    Warnings: my warning,my warning,my warning
    

    注:python 2.6+是 catch_warnings .

    2 回复  |  直到 16 年前
        1
  •  7
  •   David Z    16 年前

    看看巨蟒的 warnings 模块, http://docs.python.org/library/warnings.html

    我认为在不指定语言的情况下,您对这个问题没有什么好说的,因为不同语言之间的非终端错误处理差异很大。

        2
  •  -1
  •   Chris Ballance    16 年前

    严重错误应该冒泡,警告应该只在适当的位置记录,而不抛出异常。