Search code examples
pythonasyncpg

How to catch SQL errors with AsyncPG?


I'm having a real hard time finding any examples of how to error handle in AsyncPG. I am executing this query:

await pg_con.execute("UPDATE users set x = $1, y = $2 WHERE z = $3", x, y, z)

I want to be able to catch any SQL errors, such as if the record does not exist. How do I do this?


Solution

  • asyncpg has module exceptions with all possible exceptions. You can catch specific error, e.g.:

    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)
    

    or just catch asyncpg.PostgresError or even Exception instead. Also, it's sometimes easy to check exception detail in python interpreter:

    try:
        await pg_con.execute(query)
    except Exception as e:
        breakpoint()  # then use e.__class__, e.args, dir(e), etc