【发布时间】:2021-09-01 14:49:59
【问题描述】:
我很难找到任何关于如何在 AsyncPG 中进行错误处理的示例。 我正在执行这个查询:
await pg_con.execute("UPDATE users set x = $1, y = $2 WHERE z = $3", x, y, z)
我希望能够捕获任何 SQL 错误,例如记录不存在时。我该怎么做?
【问题讨论】:
我很难找到任何关于如何在 AsyncPG 中进行错误处理的示例。 我正在执行这个查询:
await pg_con.execute("UPDATE users set x = $1, y = $2 WHERE z = $3", x, y, z)
我希望能够捕获任何 SQL 错误,例如记录不存在时。我该怎么做?
【问题讨论】:
asyncpg 具有包含所有可能异常的模块异常。您可以捕获特定的错误,例如:
import asyncpg
try:
await pg_con.execute("UPDATE users set x = $1, y = $2 WHERE z = $3", x, y, z)
except asyncpg.ForeignKeyViolationError as e:
print('error occurred', e)
或者只是赶上asyncpg.PostgresError 甚至Exception。
此外,有时在 python 解释器中检查异常细节很容易:
try:
await pg_con.execute(query)
except Exception as e:
breakpoint() # then use e.__class__, e.args, dir(e), etc
【讨论】: