【问题标题】:How to catch SQL errors with AsyncPG?如何使用 AsyncPG 捕获 SQL 错误?
【发布时间】: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 错误,例如记录不存在时。我该怎么做?

【问题讨论】:

    标签: python asyncpg


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 2017-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多