I have just started to create a distributed system that now got a single server and a bunch of clients. The language used is python and communication is done using sockets and JSON. When an error occurs on the server-side I send the error class-name and the error arguments to the client-side like this:
except Exception as e:
jsonResult = {"error":
{
"name":e.__class__.__name__,
"args": e.args
}
}
jsonResult = json.dumps(jsonResult)
jsonResult += "\n"
return jsonResult
And then try to raise it on the client-side like this:
errorFunc = decodedReply["error"]["name"]
args = decodedReply["error"]["args"]
print (args)
# Builds and appends the argumentstring to the error class-name.
errorFunc += '('
for arg in args:
# Handles when the argument is a string.
if isinstance(arg, str):
errorFunc += '\'' + arg + '\','
else:
errorFunc += arg + ','
# Removes the extra ',' from the string before adding the last ')'.
errorFunc = errorFunc[:-1]
errorFunc += ')'
# Debugging print.
print ("Here: " + errorFunc)
raise exec(errorFunc)
When I do this I get the error
TypeError: exceptions must derive from BaseException
From what I read here: Error exception must derive from BaseException even when it does (Python 2.7)
it looks like I have to declare it as a class. Is there anyway to get around that?
According to python you are raising something which is not an exception:
>>> type(exec("ValueError('ABC')"))
<class 'NoneType'>
You need to rewrite your code to have this:
>>> errorFunc = "ValueError('ABC')"
>>> exec('raise ' + errorFunc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
ValueError: ABC