python - 如何在 python 中捕获 pg8000.core.IntegrityError 异常?
问题描述
当尝试使用pg8000加载到 postgresql 中的表时,我正在尝试运行测试用例以捕获主键异常。但是,我无法在 python 中捕捉到它。下面是我的代码。
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")
,您将看到该消息后跟引发该消息的异常。
推荐阅读
- java - 尽管没有任何改变,但简单的应用程序崩溃
- java - Redis 消费者无法消费特定事件
- python - 如果 X 列包含字符串,则在 Y 列中查找子字符串的位置 - PYTHON
- python - tkinter filedialog 没有隐藏文件夹
- flutter - 我如何在 dart-flutter 上获得代码安全性
- cypress - 从 mochawesome 报告中删除待定测试
- javascript - Express js每次重启服务器时异步执行一个函数
- c# - 如何让我的 RabbitMQ 消费者只收到一条消息而不会超时并再次发送?
- bash - 无法在 docker 容器中启动服务
- css - 如何在页面上的某个路径为类名配置样式?