Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch specific Postgres exceptions in Python psycopg2

Default psycopg2 error messages are too broad. Most of the time it simply throws:

psycopg2.OperationalError

without any additional information. So it is hard to guess, what was the real reason of the error - either incorrect user credentials, or simply the fact the server is not running. So, I need some more appropriate error handling, like error codes in pymysql library.

I've seen this page, but it does not help. When I do

except Exception as err:
    print(err.pgcode)

it always prints None. And as for errorcodes it is simply undefined. I tried to import it, but failed. So, I need some help.

like image 588
Jacobian Avatar asked Jan 23 '26 18:01

Jacobian


1 Answers

For anyone looking a quick answer:

Short Answer

import traceback  # Just to show the full traceback
from psycopg2 import errors

InFailedSqlTransaction = errors.lookup('25P02')

            try:
                feed = self._create_feed(data)
            except InFailedSqlTransaction:
                traceback.print_exc()
                self._cr.rollback()
                pass # Continue / throw ...

Long Answer

  1. Go to psycopg2 -> erros.py you will find the lookup function lookup(code).
  2. Go to psycopg2\_psycopg\__init__.py in sqlstate_errors you will find all codes to add as string into the lookup function.
like image 135
Federico Baù Avatar answered Jan 26 '26 10:01

Federico Baù



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!