How do I detect, specifically, a serialization failure when using SQL Alchemy?

388 views Asked by At

When Postgresql rolls back a transaction due to a serialization failure, that bubbles up to SQL Alchemy in the form of a DBAPIError (I believe newer versions raise an OperationalError instead). But I want to know whether the issue was serializability (in which case I can retry the transaction) or something else (in which case I might want to present an error to the user).

I could catch the exception and read its string representation:

try:
    ... # Statement causing a serialization failure
except DBAPIError as e:
    if str(e).find("could not serialize access due to read/write dependencies among transactions") >= 0:
        # Retry
    else:
        # Report error

But I fear this is not robust and it feels wrong to be checking strings.

Is there a better way?

0

There are 0 answers