6

エラーと警告の両方の詳細を伝達するための共通のパターンはありますか? エラーとは、コードの流れを停止させる深刻な問題を意味します。警告とは、ユーザーに問題を通知する価値はあるものの、あまりにも些細なことでプログラムの流れを止めることができない問題を意味します。

現在、例外を使用してハード エラーを処理し、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

4

2 に答える 2

7

Python のwarningsモジュールを調べてください。 http://docs.python.org/library/warnings.html

非端末エラーの処理は言語によって大きく異なるため、言語を指定せずにこの問題について言えることはあまりないと思います。

于 2009-02-23T20:05:54.827 に答える
-1

重大なエラーは発生し、警告は例外をスローせずにログに記録する必要があります。

于 2009-02-23T20:00:00.130 に答える