class '_mysql_exceptions.DataError': 如何在 if 条件下检查变量类型

class '_mysql_exceptions.DataError': How to check a variable type in an if condition

我需要returnupdate/insert结果,从数据库class,返回调用class来区分 在成功与错误之间。
一个 update/insert returns <type long'> 而一个数据库错误 returns
<class '_mysql_exceptions.DataError'>.
由于我不确定成功期间的 return 类型是否始终是长类型,因此我正在检查类型 class.
而且,我做不到。我试过这些:

 try:
   x = cursor.execute(q, d)
   conn.commit()
   return x   #Return this to the calling class
 except MySQLdb.Error, e:
   return e   #Return this to the calling class

 if isinstance(e, class): #Doesn't work
 if issubclass(e, _mysql_exceptions): #Doesn't work

如何在此处查看 e 的类型?
如果我做错了,请推荐一些好的,谢谢。

问题是 isinstance(obj, class) 不是有效的语法,_mysql_exceptions 是一个模块,而不是引发 TypeError 的异常类型。要显式检查异常类型,您可以单独捕获每个异常类型:

from _mysql.exceptions import DataError, SomeOtherError, ...
from requests import HTTPError # as an example of a different error

try:
    x = cursor.execute(q, d)
    conn.commit()
except DataError as e:
    # do something
except SomeOtherError as e:
    # do something else
except HTTPError as e:
    # your connection is broken
    # maybe raise from e?

您需要捕获该明确的错误类型,然后您不需要做 if isinstance。从根本不处理任何异常开始,这将导致您 do 需要处理的异常,其他任何情况都应视为意外,并应导致应用程序崩溃或传播一些异常有用的错误消息,让您知道发生了不好的事情:

try:
    some_function()
except ValueError as e:
    # this is expected, and is handled accordingly
    handle_expected_error()

# This is optional, normally a bare exception block is considered bad practice,
# but can allow your application to continue functioning while raising some
# helpful error so this isn't suppressed
except Exception as e:
    # this is not expected, I'm going to propagate this error
    # up to be obvious what happened
    handle_unexpected_error()
    #or
    raise from e

编辑:如果我想要调用 class 来处理异常怎么办?

合理,我会倾向于捕获异常。我不处理异常,而是允许函数只引发异常并在调用 class 中处理它。作为一个非常简单的例子:

class MyClass:
    def __init__(self, conn, cursor):
        self.conn = conn
        self.cursor = cursor

    def some_function(self):
        # This raises an error, note I'm not handling it here
        x = self.cursor.execute()
        self.conn.commit()
        return x

    def main_function(self):
        try:
            x = self.some_function()
        except DataError as e:
            handle_exception()
        # unexpected, handle this here
        except Exception as e:
            raise from e
            # or do something else