What is the best way to collect errors and send a summary?
<p>I have a script executing several independent functions in turn. I would like to collect the errors/exceptions happening along the way, in order to send an email with a summary of the errors.</p>

<p>What is the best way to raise these errors/exceptions and collect them, while allowing the script to complete and go through all the steps? They are independent, so it does not matter if one crashes. The remaining ones can still run.</p>

<pre><code>def step_1():
    # Code that can raise errors/exceptions

def step_2():
    # Code that can raise errors/exceptions

def step_3():
    # Code that can raise errors/exceptions

def main():
    step_1()
    step_2()
    step_3()

    send_email_with_collected_errors()

if '__name__' == '__main__':
    main()
</code></pre>

<p>Should I wrap each step in a try..except block in the main() function? Should I use a decorator on each step function, in addition to an error collector?</p>

<p>There are two options:</p>

<ol>
<li>Use decorator in which you catch all exceptions and save it somewhere.</li>
<li>Add try/except everywhere.</li>
</ol>

<p>Using decorator might be much better and cleaner, and code will be easier to maintain.</p>

<p>How to store errors? Your decision. You can add them to some list, create logging class receiving exceptions and get them after everything is doneâ¦ Depends on your project and size of code.</p>

<p>Simple logging class:</p>

<pre><code>class LoggingClass(object):
    def __init__(self):
        self.exceptions = []

    def add_exception(self, exception):
        self.exceptions.append(exception)

    def get_all(self):
        return self.exceptions
</code></pre>

<p>Create instance of class in your script, catch exceptions in decorator and add them to class (however global variable might be also ok).</p>

python