Handling PyMySql exceptions - Best Practices

2024/10/6 14:23:17

My question regards exception best practices. I'll present my question on a specific case with PyMySQL but it regards errors handling in general. I am using PyMySQL and out of the many possible exceptions, there is one I want to deal with in a specific manner. "Duplicate" exception.

pymysql maps mysql errors to python errors according to the following table:

_map_error(ProgrammingError, ER.DB_CREATE_EXISTS, ER.SYNTAX_ERROR,ER.PARSE_ERROR, ER.NO_SUCH_TABLE, ER.WRONG_DB_NAME,ER.WRONG_TABLE_NAME, ER.FIELD_SPECIFIED_TWICE,ER.INVALID_GROUP_FUNC_USE, ER.UNSUPPORTED_EXTENSION,ER.TABLE_MUST_HAVE_COLUMNS, ER.CANT_DO_THIS_DURING_AN_TRANSACTION)
_map_error(DataError, ER.WARN_DATA_TRUNCATED, ER.WARN_NULL_TO_NOTNULL,ER.WARN_DATA_OUT_OF_RANGE, ER.NO_DEFAULT, ER.PRIMARY_CANT_HAVE_NULL,ER.DATA_TOO_LONG, ER.DATETIME_FUNCTION_OVERFLOW)
_map_error(IntegrityError, ER.DUP_ENTRY, ER.NO_REFERENCED_ROW,ER.NO_REFERENCED_ROW_2, ER.ROW_IS_REFERENCED, ER.ROW_IS_REFERENCED_2,ER.CANNOT_ADD_FOREIGN, ER.BAD_NULL_ERROR)
_map_error(NotSupportedError, ER.WARNING_NOT_COMPLETE_ROLLBACK,ER.NOT_SUPPORTED_YET, ER.FEATURE_DISABLED, ER.UNKNOWN_STORAGE_ENGINE)
_map_error(OperationalError, ER.DBACCESS_DENIED_ERROR, ER.ACCESS_DENIED_ERROR,ER.CON_COUNT_ERROR, ER.TABLEACCESS_DENIED_ERROR,ER.COLUMNACCESS_DENIED_ERROR)

I want to specifically catch ER.DUP_ENTRY but I only know how to catch IntegrityError and that leads to redundant cases within my exception catch.

cur.execute(query, values)
except IntegrityError as e:if e and e[0] == PYMYSQL_DUPLICATE_ERROR:handel_duplicate_pymysql_exception(e, func_a)else:handel_unknown_pymysql_exception(e, func_b)
except Exception as e:handel_unknown_pymysql_exception(e, func_b)

Is there a way to simply catch only ER.DUP_ENTRY some how? looking for something like:

except IntegrityError.DUP_ENTRY as e:handel_duplicate_pymysql_exception(e, func_a)

Thanks in advance for your guidance,

Answer

there is very generic way to use pymysql error handling. I am using this for sqlutil module. This way you can catch all your errors raised by pymysql without thinking about its type.

try:connection.close()print("connection closed successfully")
except pymysql.Error as e:print("could not close connection error pymysql %d: %s" %(e.args[0], e.args[1]))
https://en.xdnf.cn/q/70362.html

Related Q&A

Beautifulsoup find element by text using `find_all` no matter if there are elements in it

For examplebs = BeautifulSoup("<html><a>sometext</a></html>") print bs.find_all("a",text=re.compile(r"some"))returns [<a>sometext</a>] …

Python: how to get values from a dictionary from pandas series

I am very new to python and trying to get value from dictionary where keys are defined in a dataframe column (pandas). I searched quite a bit and the closest thing is a question in the link below, but…

Django No Module Named URLs error

There are many similar questions posted already, but Ive already tried those solutions to no avail. Im working through a basic Django tutorial, and here is my code:urls.pyfrom django.conf.urls import …

Matplotlib artist to stay same size when zoomed in but ALSO move with panning?

This is a very direct follow-up on this question.Using matplotlib, Id like to be able to place a sort of "highlighting bar" over a range of data markers that I know will all be in a straight …

How to invoke Lambda function with Event Invocation Type via API Gateway?

Docs says:By default, the Invoke API assumes RequestResponse invocation type. You can optionally request asynchronous execution by specifying Event as the InvocationType. So all I can send to my functi…

How do I unlock the app engine database when localhost runs?

Right now I get a blank page when localhost runs, but the deployed app is fine. The logs show the "database is locked". How do I "unlock" the database for localhost?

PyCrypto: Generate RSA key protected with DES3 password

I have been able to create a RSA key protected by password with DES3 (well... I think because Im very new to this encryption world) by using the command:openssl genrsa -out "/tmp/myKey.pem" -…

Normalize/Standardize a numpy recarray

I wonder what the best way of normalizing/standardizing a numpy recarray is. To make it clear, Im not talking about a mathematical matrix, but a record array that also has e.g. textual columns (such as…

How to read /dev/log?

I would like to directly access to syslog messages from Python by reading /dev/log.My (very limited) understanding is that the correct way is to read from there is to bind a datagram socket. import soc…

Determining if a number evenly divides by 25, Python

Im trying to check if each number in a list is evenly divisible by 25 using Python. Im not sure what is the right process. I want to do something like this:n = [100, 101, 102, 125, 355, 275, 435, 134, …