Psycopg passes the PostgreSQL error code along with an exception to the attribute pgcode: you can verify that the error is actually associated with a unique violation and does not allow them to be written. For instance:
try:
cursor.execute("...")
except psycopg2.IntegrityError as err:
if err.pgcode != '23505':
logger.error('FunctionName: %s', err)
except Exception as err:
logger.error('FunctionName: %s', err)
source
share