[英]Python/Django: how do I determine the class to specify in an “except” statement?
我正在使用一些繼承的Python / Django代碼。 在其中有一個用try塊包圍的DB調用,帶有“ except Exception ex”語句以捕獲所有異常。 我希望更具選擇性,並且僅捕獲我預期的異常類型。 通過檢查捕獲的Exception對象,我可以知道它的類型為“ DatabaseError”。
下面的代碼中的注釋顯示了我在Googling問題並在此處搜索的過程中嘗試過的許多事情,以及Python在嘗試時給我的錯誤。 最令人沮喪的是,我在人們說有效的代碼網絡上找到了很多示例,就像我正在嘗試的那樣。 但是我發現的代碼示例通常不包含“ import”行。
我懷疑我需要再導入一些東西,但是我不知道是什么。
import cx_Oracle
## import cx_Oracle.DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
## from cx_Oracle import DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
. . .
connection = connections['ims_db']
sqlUpdateQuery = "SELECT * FROM LOCKING WHERE IDENT={0} AND KEY_ID='SL_KEY' FOR UPDATE NOWAIT".format(self.serviceUid)
cursor = connection.cursor()
try:
cursor.execute(sqlUpdateQuery)
# this gets the error "Undefined variable 'Database'"
## except Database.DatabaseError as dbe3:
# this gets the error "Undefined variable 'Oracle'"
## except Oracle.DatabaseError as dbe2:
# this gets the error "Module 'cx_Oracle' has no 'DatabaseError' member"
## except cx_Oracle.DatabaseError as dbe:
# this gets the error "Undefined variable 'DatabaseError'"
## except DatabaseError as dbe:
# this gets the error "Catching an exception which doesn't inherit from BaseException: cx_Oracle"
## except cx_Oracle as dbe:
# this gets the error "Module cx_Oracle has no '_error' member"
## except cx_Oracle._Error as dbe:
except Exception as ex:
# This gets the error "Module cx_Oracle has no 'DatabaseError' member"
## if isinstance(ex, cx_Oracle.DatabaseError) :
# This gets the error "Undefined variable 'DatabaseError'"
## if isinstance(ex, DatabaseError) :
className = type(ex).__name__
# This logs "... class = DatabaseError ..."
log.error("Exception (class = {1}) while locking service {0}".format(self.serviceUid, className))
args = ex.args
arg0=args[0]
# arg0ClassName is "_Error"
arg0ClassName = type(arg0).__name__
code = arg0.code
# codeClassName is "int"
codeClassName = type(code).__name__
msg = "Exception, code = {0}".format(code)
log.debug(msg)
raise
正確的語法如下:
try:
cur.execute("some_sql_statement")
except cx_Oracle.DatabaseError as e:
error, = e.args
print("CONTEXT:", error.context)
print("MESSAGE:", error.message)
您可以在以下幾個示例(如TypeHandlers.py)中看到該語法: https : //github.com/oracle/python-cx_Oracle/tree/master/samples 。
嘗試運行示例並與它們一起使用,以查看是否可以解決問題。 如果不是,請在此處創建一個包含完整可運行示例的問題: https : //github.com/oracle/python-cx_Oracle/issues 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.