Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Psycopg2 error messages

All,

I am writing error messages to a log file and it's becoming pretty large because it errors on unique constraints in the DB. That is fine and it's actually want it to do so my question is, how can I avoid writing the duplicate key errors to the log file every time they happen?

        except Exception as err:
                logger.error('FunctionName: %s',  err)

Thanks, Adam

like image 269
aeupinhere Avatar asked Jul 14 '11 17:07

aeupinhere


1 Answers

Psycopg passes the PostgreSQL error code along with the exception in the attribute pgcode: you can verify that the error is actually related to a unique violation and avoid logging them. For example:

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)
like image 106
piro Avatar answered Sep 28 '22 03:09

piro