Catching the exception tracebacks in a loop and then raising the error(s) at the end of the script

Ryflex

I'm trying to catch all exception error(s) and then at the end of the script for it to raise/show all tracebacks...

I have a main script that calls my subscripts for example:

    errors = open('MISC/ERROR(S).txt', 'a')

    try:
        execfile("SUBSCRIPTS/Test1.py", {})
    except Exception:
        ## Spread over two calls of errors.write for readability in code...
        errors.write(strftime('%d/%m/%Y %H:%M:%S') + "\n")
        errors.write(traceback.format_exc() + '\n\n')

    try:
        execfile("SUBSCRIPTS/Test2.py", {})
    except Exception:
        ## Spread over two calls of errors.write for readability in code...
        errors.write(strftime('%d/%m/%Y %H:%M:%S') + "\n")
        errors.write(traceback.format_exc() + '\n\n')

    errors.close()

This script uses the traceback module to retrieve the error from the script...

In the next example this is what my current script sort of looks like:

for x in y:
    if "example" in x:
        for tweet in tweetlist:
            # Try
            try:
                twitter.update_status(status=tweet)
                # Do some other stuff here if it suceeeds like...
                print "oo example worked"
            # Damn it failed, grab the whole traceback?
            except Exception as reason:
                FailedTweet = True

# Do some other stuff here like...
print "I did other stuff"

if FailedTweet:
    print reason # Printing the reason because I don't know how to throw the exception error (full error)

Basically there is a big loop where it could potentially go wrong around the line: twitter.update_status(status=tweet) and if it does I want it to catch the traceback error(s) could be more than one because it's in a loop and then when the script finishes I want it to send all the traceback errors back to the main script so it can write them all to the error file.

Example of the error writing to file from the first bit of code:

# 17/08/2014 12:30:00
# Traceback (most recent call last):
#   File "C:\Main.py", line 117, in execute_subscripts
#     execfile("SUBSCRIPTS/Test1.py", {})
#   File "SUBSCRIPTS/Test1.py", line 440, in <module>
#     twitter.update_status(status=string)
#   File "C:\Python27\lib\site-packages\twython\endpoints.py", line 90, in update_status
#     return self.post('statuses/update', params=params)
#   File "C:\Python27\lib\site-packages\twython\api.py", line 234, in post
#     return self.request(endpoint, 'POST', params=params, version=version)
#   File "C:\Python27\lib\site-packages\twython\api.py", line 224, in request
#     content = self._request(url, method=method, params=params, api_call=url)
#   File "C:\Python27\lib\site-packages\twython\api.py", line 194, in _request
#     retry_after=response.headers.get('retry-after'))
# TwythonError: Twitter API returned a 403 (Forbidden), This request looks like it might be automated. To protect our users from spam and other malicious activity, we can't complete this action right now. Please try again later.

How would I achieve this, it's kind of hard to explain so if something doesn't make sense please ask.

dano

Just save the traceback data in a list, and then print the contents of the list after the loop is complete.

import traceback

reasons = []
for x in y:
    if "example" in x:
        for tweet in tweetlist:
            # Try
            try:
                twitter.update_status(status=tweet)
                # Do some other stuff here if it suceeeds like...
                print "oo example worked"
            # Damn it failed, grab the whole traceback?
            except Exception:
                reasons.append(traceback.format_exc())

# Do some other stuff here like...
print "I did other stuff"

for reason in reasons:
    print reason

# If you want to raise a single exception that shows the traceback for
# each exception, you can do this:
class ChainedException(Exception):
    def __init__(self, msg):
        msg = "The following exceptions occurred:\n\n{}".format(msg)

if reasons:
    raise ChainedException('\n'.join(reasons))

Example usage of ChainedException:

reasons = []
for i in range(5):
    try:
        raise Exception("Blah {}".format(i))
    except Exception:
        reasons.append(traceback.format_exc())

if reasons:
    raise ChainedException("\n".join(reasons))

Output:

Traceback (most recent call last):
  File "ok.py", line 17, in <module>
    raise ChainedException("\n".join(reasons))
__main__.ChainedException: The following exceptions occurred:

Traceback (most recent call last):
  File "ok.py", line 12, in <module>
    raise Exception("Blah {}".format(i))
Exception: Blah 0

Traceback (most recent call last):
  File "ok.py", line 12, in <module>
    raise Exception("Blah {}".format(i))
Exception: Blah 1

Traceback (most recent call last):
  File "ok.py", line 12, in <module>
    raise Exception("Blah {}".format(i))
Exception: Blah 2

Traceback (most recent call last):
  File "ok.py", line 12, in <module>
    raise Exception("Blah {}".format(i))
Exception: Blah 3

Traceback (most recent call last):
  File "ok.py", line 12, in <module>
    raise Exception("Blah {}".format(i))
Exception: Blah 4

Edit:

If you really only care about raising a single exception out of the entire list of exceptions, you can do it like this:

import traceback

reason = None
for x in y:
    if "example" in x:
        for tweet in tweetlist:
            # Try
            try:
                twitter.update_status(status=tweet)
                # Do some other stuff here if it suceeeds like...
                print "oo example worked"
            # Damn it failed, grab the whole traceback?
            except Exception:
                reason = sys.exc_info() # We're not putting it in a list because you only care about one.

# Do some other stuff here like...
print "I did other stuff"

if reason:
    raise reason[0], reason[1], reason[2]

Note that this only works in Python 2.x. If you were using Python 3.x, you would need to use this:

if reason:
    raise reason[1].with_traceback(reason[2])

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related