Handling exception coming from the server/uplink modules

I got around this issue by doing something like this:

First, I create a custom Exception on the server side that looks like this:

class MyException(Exception):
    def __str__(self):
        return "<{}> {}".format(type(self).__name__, " ".join(self.args))

This means that when __str__ is called to represent the Exception, it will return a string that contains the name of the custom Exception class as well as any messages passed to it as an argument, so:

>>> print(MyException('Hi!'))
<MyException> Hi!
>>>

In that case, on the client side, your handler would look like this:

try:
    foo()  # Any routine that can throw the custom Exception.
except Exception as e:
    if '<MyException>' in str(e):
        print('Caught it')
    else:
        raise e

You catch every exception that comes across on the client side, but you only handle them if their string matches your known tags, otherwise, you raise them again. Maybe not 100% perfect, but it seems to work so far.

2 Likes