Josh Honig
Josh Honig

Reputation: 187

Manually raising exceptions over Python XML-RPC

Solution at the bottom of this question!

In my situation, my client sends data to the server to do CPU-intensive workloads. I would like for my XML-RPC server to be able to raise an exception when there is a problem with the input data.

I have tried a simple raise Exception('description of the error') on the server side, but on my client, I get: xmlrpc.client.Fault: <Fault 1: "<class 'TypeError'>:exceptions must derive from BaseException">

On the client side, I would like to be able to do the following:

try:
    proxy.processData(data)
except:
    [... code to handle the exception ...]

and on the server side:

def processData(data):
    if 'somethingRequired' not in data:
        raise Exception('Something Required not in data!')
    [... continue processing ...]

I think it may also be ideal to have the exception be a custom type on the client side, so that exceptions caused by the XML-RPC module (for example, not being able to connect to the XML-RPC server) don't get interpreted as data input errors.

Thanks!

Update: Solution

Above my processData method, I added the following (a custom exception):

class ProcessingError(Exception):
    pass

then, in my client code, I used the following for error handling::

try:
    proxy.processData(data)
except xmlrpc.client.Fault as e:
    print(e.faultString)

Note that if you would like to differentiate between custom exceptions and exceptions from the XML-RPC module (like connection errors), you can parse str(e) in the except: block to check if your exception was in the error or not. I don't have that in my code above.

The xmlrpc.client.Fault class has a few attributes that can be found here.

Upvotes: 2

Views: 1767

Answers (1)

Data_Is_Everything
Data_Is_Everything

Reputation: 2016

May need to raise custom exception in your case, Exception is trying to refer to a parent class, which you maybe missing. Something like this:

class SomeSortOfException(Exception):
   pass

This should be at the top or before the scope of the processData() function.

Upvotes: 2

Related Questions