Mark Reddington
Mark Reddington

Reputation: 153

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?

Upvotes: 6

Views: 2363

Answers (1)

ifrag
ifrag

Reputation: 161

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

Upvotes: 4

Related Questions