如何在python中捕获pg8000.core.IntegrityError异常



当我试图使用pg8000加载到postgresql中的表中时,我正试图运行一个测试用例来捕获主键异常。但是,我无法用蟒蛇捕捉到它。下面是我的代码。

import pg8000
def create_albums(self,music):
experts = []
exp = music.data_info.get("artist_list")  # List of a dictionary
try:
for expert in exp:
experts.append(ArtistData({
"name": expert.name,
"age": expert.age,
"present": True,
"nodiscs": expert.get("disc_code")
}))
except pg8000.core.IntegrityError:
raise Exception
return experts

以下是错误消息

pg8000.core.IntegrityError: {'S': 'ERROR', 'V': 'ERROR', 'C': '23505', 'M': 'duplicate key value violates unique constraint "artist_discs_pkey"}

非常感谢您的帮助。非常感谢。

您确实捕获了异常,但您所做的只是再次引发它,所以它相当无用。

在引发之前添加一个简单的打印,例如print("Failed to insert"),您将看到该消息后面跟着引发它的exeption

根据文档,

"pg8000.core.IntegrityError:";属于泛型(数据库错误(。所以你需要像这样格式化你的代码,用DatabaseError:代替IntegrityError

import pg8000
def create_albums(self,music):
experts = []
exp = music.data_info.get("artist_list")  # List of a dictionary
try:
for expert in exp:
experts.append(ArtistData({
"name": expert.name,
"age": expert.age,
"present": True,
"nodiscs": expert.get("disc_code")
}))
except pg8000.core.DatabaseError:
raise Exception
return experts

相关内容

  • 没有找到相关文章

最新更新