【问题标题】:Python/PyHive - extract specific error message from exceptionPython/PyHive - 从异常中提取特定的错误消息
【发布时间】:2019-02-22 19:00:17
【问题描述】:

我正面临similar to this one 异常,我正在尝试根据错误本身来处理它。 问题是pyhive.exc.OperationalError 非常通用,可以处理从超时到不存在的表的错误,所以我需要来自errorMessage 部分的确切值,以便以不同的方式处理每种错误类型,比如超时,等待并重试;如果是别的东西,以不同的方式处理,依此类推。

如果我将错误捕获为except OperationalError as e,我将如何提取errorMessage 部分?我可以解析字符串表示 (e.__str__()),但这似乎很奇怪,因为我确信有正确的方法。

【问题讨论】:

  • 我也在寻找这个问题的解决方案。如果你找到了请分享

标签: python error-handling pyhive


【解决方案1】:

如果你看到实现hive Exception implementation,它只是继承了Exception 所以它只有字符串格式的异常细节,看起来有点像json,这实际上让我们感到困惑,我们希望使用实例变量来访问它或作为字典,但实际上它只是看起来像 json 的字符串。

但我们可以使用正则表达式来提取我们希望的细节,例如errortype 等。

【讨论】:

    【解决方案2】:

    我找到了另一种方法,这似乎是更好的方法。

     try:
            return presto.execute_query_safe(query, bind_params)
     except pyhive.exc.DatabaseError as e:
            logging.error("Query failed", exc_info=1)
            if error.args[0]['errorName'] == 'SYNTAX_ERROR' or error.args[0]['errorType'] == 'USER_ERROR':
                raise NonRecoverableQueryError('Non Recoverable Error: ' + str(error))
            raise e
    

    【讨论】:

      【解决方案3】:

      你可以这样提取errorMessage

      from pyhive import hive, exc
      
      try:
        connection = hive.connect(host="localhost", port=10000)
        cursor = connection.cursor()
        cursor.execute(sql_string)
      except exc.Error as e:
        error_message = e.args[0].status.errorMessage
        print(error_message)
      

      您可以使用dir(e) 查找每个对象的方法和dunder 方法。这将允许您查看可以调用哪些方法来访问数据。

      【讨论】:

        猜你喜欢
        • 2011-05-26
        • 1970-01-01
        • 2020-08-04
        • 2014-08-11
        • 1970-01-01
        • 2014-04-17
        • 2017-02-11
        • 1970-01-01
        • 2012-10-08
        相关资源
        最近更新 更多