我刚刚开始创建一个分布式系统,该系统现在具有一台服务器和一堆客户端。使用的语言是python,通信使用套接字和JSON完成。当服务器端发生错误时,我将错误类名和错误参数发送给客户端,如下所示:
except Exception as e:
jsonResult = {"error":
{
"name":e.__class__.__name__,
"args": e.args
}
}
jsonResult = json.dumps(jsonResult)
jsonResult += "\n"
return jsonResult
然后尝试像这样在客户端上提高它:
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)
当我这样做时,我得到了错误
TypeError: exceptions must derive from BaseException
根据我在这里所读的内容:即使异常也必须从BaseException派生出来(Python 2.7)
看来我必须将其声明为类。反正有解决这个问题的方法吗?
根据python,您提出了一些例外情况:
>>> type(exec("ValueError('ABC')"))
<class 'NoneType'>
您需要重写代码以具有以下功能:
>>> 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句