Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an object with an Exception?

What is the correct way to pass an object with a custom exception? I'm pretty sure this code used to work, but now it is throwing an error.

class FailedPostException(Exception):
    pass

def post_request(request):
    session = requests.Session()
    response = session.send(request.prepare(), timeout=5, verify=True)

    if response.status_code is not requests.codes.ok:
        raise FailedPostException(response)

    session.close()
    return response

try:
    ...
except FailedPostException as r:
    // type(r) - Requests.Response
    print r.text

AttributeError: 'FailedPostException' object has no attribute 'text'
like image 715
Shane Avatar asked Apr 21 '26 14:04

Shane


1 Answers

The raising and catching of the exception is correct, the issue here is that you expect the exception to have a text attribute that does not exist. When inheriting from a built-in exception type you can use the args attribute, which will be a tuple of the arguments to the exception, for example:

try:
    ...
except FailedPostException as r:
    print r.args[0]

In this case you could use str(r) instead of r.args[0]. If there is only one argument to the exception then str(r) will be equivalent to str(r.args[0]), otherwise it will be equivalent to str(r.args).

If you want to add the text attribute to your FailedPostException, you can do the following:

class FailedPostException(Exception):
    def __init__(self, text, *args):
        super(FailedPostException, self).__init__(text, *args)
        self.text = text

Note that in Python 3.x you can just use super().__init__(text, *args).

like image 191
Andrew Clark Avatar answered Apr 24 '26 04:04

Andrew Clark