A Word About psycopg2 Exceptions

redhap

HAP

Posted on November 3, 2021

A Word About psycopg2 Exceptions

And the word is "Information."

There is a wealth of information that is captured in the psycopg2 exceptions. These exceptions not only capture a (slightly) reformatted message in the standard args attribute, but also have more attributes that have information from the driver and the cursor and connection classes.

The extra attributes are:

Attribute Description
cursor The executing cursor during the exception|
diag An object that contains extra information regarding the context and the statement that was running. This may also capture syntax errors in the SQL.
pgcode The raw PostgreSQL error code
pgerror The raw PostgreSQL error message|

So what does that do for you? The cursor attribute is a cursor object. This means that you have access to the last run query as well as the connection. So those can be probed for more information such as the query text and the connection back-end pid. The diag can help with sql statement syntax errors. The pgcode and pgerror can be useful for lower-level analysis, if needed.

Be aware that if you need to query the DB for more information during an exception, you should use a separate connection to get it as an exception state from SQL execution will put the transaction in a state that must be rolled back.

With Django exceptions, you need to access a dunder attribute to get to the information you will need. Django exceptions for the database will most likely only have the args attribute. But it does have the __cause__ attribute which should be the original driver exception instance. And from that instance, you can access the other attributes.

This can prove quite helpful if you need more information quickly without actually trying to access search and parse database log information.

See the this documentation for more information regarding the psycopg2 exception classes representing PostgreSQL errors.

Happy coding and happy exception handling!

💖 💪 🙅 🚩
redhap
HAP

Posted on November 3, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

A Word About psycopg2 Exceptions
postgres A Word About psycopg2 Exceptions

November 3, 2021