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.
2
Answers
Meanwhile, I have implemented by catching a generic
Exception
and checking if the exception belongs to the list returned bydir(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 psycopgerrors
:Then, I use this function in the try/except clause:
For my very specific case, where I need to check for other other exceptions as well, I can readapt Yannick solution as follows:
You can you use the base class
psycopg2.Error
it catch all psycopg2 related errorssee official documentation