是否有传播错误和警告细节的通用模式?通过错误我的意思是严重的问题,应该引起的码流停止.通过警告我的意思是值得告知用户问题的问题,但是太过微不足以阻止程序流程.
我目前使用异常来处理硬错误,并使用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 "", line 1, in File " ", 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
.
查看Python的warnings
模块,http://docs.python.org/library/warnings.html
我不认为在没有指定语言的情况下你可以对这个问题说多少,因为非终端错误处理因语言而异.