Search code examples
pythonpostgresqlpsycopg2

Catch any of the errors in psycopg2 without listing them explicitly


I have a try and except block where I would like to catch only the errors in the psycopg2.errors and not any other error.

The explicit way would be:

try:
    # execute a query
    cur = connection.cursor()
    cur.execute(sql_query)
except psycopg2.errors.SyntaxError, psycopg2.errors.GroupingError as err:
    # handle in case of error

The query will always be some SELECT statement. If the execution fails it should be handled. Any other exception not belonging to psycopg, e.g. like ZeroDivisionError, should not be caught from the except clause. However, I would like to avoid to list all errors after the except clause. In fact, if you list the psycopg errors, you get a quite extensive list:

from psycopg2 import errors
dir(errors)

I have searched quite extensively and am not sure if this question has been asked already.


Solution

  • You can you use the base class psycopg2.Error it catch all psycopg2 related errors

    import psycopg2
    
    try:
       cur = connection.cursor()
       cur.execute(sql_query)
    except psycopg2.Error as err:
       # handle in case of error
       
    

    see official documentation