Home > database >  Catch any of the errors in psycopg2 without listing them explicitly
Catch any of the errors in psycopg2 without listing them explicitly

Time:12-16

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.

CodePudding user response:

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

CodePudding user response:

Meanwhile, I have implemented by catching a generic Exception and checking if the exception belongs to the list returned by dir(errors). The solution proposed by Yannick looks simpler, though.

The function that I use prints the error details and checks using the name of the exception err_type.__name__ whether it is in any of the psycopg errors:

from psycopg2 import errors

def is_psycopg2_exception(_err):
    err_type, err_obj, traceback = sys.exc_info()
    print ("\npsycopg2 ERROR:", _err, "on line number:", traceback.tb_lineno)
    print ("psycopg2 traceback:", traceback, "-- type:", err_type)
    return err_type.__name__ in dir(errors)

Then, I use this function in the try/except clause:

try:
    # execute a query
    cur = connection.cursor()
    cur.execute(sql_query)
except Exception as err:
    if is_psycopg2_exception(err):
        # handle in case of psycopg error
    else:
        # other type of error
        sys.exit(1)  # quit

For my very specific case, where I need to check for other other exceptions as well, I can readapt Yannick solution as follows:

try:
    # execute a query
    cur = connection.cursor()
    cur.execute(sql_query)
except psycopg2.OperationalError as err:
    # handle some connection-related error
except psycopg2.Error as err:
    # handle in case of other psycopg error
except Exception as err:
    # any other error
    sys.exit(1)  # quit
  • Related