【问题标题】:Distributed system: Raise error thrown on server side on client side分布式系统:在客户端的服务器端引发错误
【发布时间】:2017-02-01 10:10:05
【问题描述】:

我刚刚开始创建一个分布式系统,现在只有一个服务器和一堆客户端。使用的语言是 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

从我在这里读到的:Error exception must derive from BaseException even when it does (Python 2.7)

看来我必须将它声明为一个类。有没有办法解决这个问题?

【问题讨论】:

  • 你能显示print ("Here: " + errorFunc)的输出吗?
  • Here: ValueError('ABC') 是输出。该错误是我在服务器端手动提出的。
  • 检查我的答案
  • 耐心是一种美德:P

标签: python python-3.x error-handling distributed-system raiserror


【解决方案1】:

根据 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多