Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python conditional exception messages

Tags:

python

I'm using Python 2.7 and am new to custom exceptions. I've read up on them as much as I can but haven't found much help for this particular issue.

I am calling an API which returns a status code with most responses. For example, 0 is 'Success', 1 is 'Wrong number of parameters', 2 is 'Missing parameter', etc.

When I get a response, I check the status to make sure I don't continue if something is wrong. I've been raising a generic exception, for example:

if response.get('status') != 0:
    print 'Error: Server returned status code %s' % response.get('status')
    raise Exception

How can I create a custom exception that looks up what the status code is and returns it as part of the exception's error message? I envision something like:

if response.get('status') != 0:
    raise myException(response.get('status'))
like image 688
AutomaticStatic Avatar asked Jun 22 '15 01:06

AutomaticStatic


People also ask

How do I capture an exception message in Python?

To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e . You can now print the error message with "print(e)" or use it for further processing.


1 Answers

So you can define a custom exception class by sub-classing Exception:

Example:

class APIError(Exception):
    """An API Error Exception"""

    def __init__(self, status):
        self.status = status

    def __str__(self):
        return "APIError: status={}".format(self.status)


if response.get('status') != 0:
    raise APIError(response.get('status'))

By sub-classing the standard Exception class of which all default/built-in exceptions inherit from you can also catch your custom exception quite easily:

try:
    # ...
except APIError as error:
    # ...

See: User-defined Exceptions

like image 149
James Mills Avatar answered Sep 21 '22 11:09

James Mills