How to catch specific exceptions on sqlalchemy?

2024/4/15 2:17:31

I want to catch specific exceptions like UniqueViolation on sqlalchemy.

But sqlalchemy throw exceptions only through IntegrityError.

So I catched specific exceptions with below code.

except sqlalchemy.exc.IntegrityError as e:from psycopg2 import errorsif isinstance(e.orig, errors.UniqueViolation):passelif isinstance(e.orig, errors.ForeignKeyViolation):pass

But it looks doesn't elegant.

I don't want to using if statement just catch with specific exception name.

Is there any way to solve this issue?

Thanks.

Answer

You can reraise the original exception from the except block and catch whatever specific type you are interested in:

import sqlalchemy
import psycopg2
from psycopg2 import errorstry:raise sqlalchemy.exc.IntegrityError("INSERT INTO table (col1) VALUES (?)", (1,), errors.IntegrityConstraintViolation)
except sqlalchemy.exc.IntegrityError as sqla_error:try:raise sqla_error.origexcept (errors.UniqueViolation, errors.ForeignKeyViolation):pass

This will raise all subclasses of psycopg2.IntegrityError other than psycopg2.error.UniqueViolation and psycopg2.errors.ForeignKeyViolation.

As stated in SuperShoot's answer, this will result in a nested exception. You can suppress the exception contex via:

raise sqla_error.orig from None

However, that might take away from the expressiveness of the traceback.

If you want to fall back to the SQLAlchemy IntegrityError if .orig is not of a type you are interested in, you can raise it again by adding this to the above:

    except psycopg2.IntegrityError:raise sqla_error from None
https://en.xdnf.cn/q/72973.html

Related Q&A

numpy.linalg.LinAlgError: SVD did not converge in Linear Least Squares on first run only

I have been wrestling with a known and documented SVD converge issue. Having read up on similar issues raised by others, I have double checked my data and reduced this to a tiny DataFrame - 10 rows/2 c…

Seaborn kde plot plotting probabilities instead of density (histplot without bars)

I have a question about seaborn kdeplot. In histplot one can set up which stats they want to have (counts, frequency, density, probability) and if used with the kde argument, it also applies to the kde…

How can I improve my code for euler 14?

I solved Euler problem 14 but the program I used is very slow. I had a look at what the others did and they all came up with elegant solutions. I tried to understand their code without much success.Her…

Visual Studio Code not recognizing Python import and functions

What do the squiggly lines represent in the image? The actual error the flags up when I hover my mouse over the squiggly line is: Import "pyspark.sql.functions" could not be resolvedPylance …

Pandas interpolate() backwards in dataframe

Going forward, interpolate works great:name days 0 a NaN 1 a NaN 2 a 2 3 a 3 4 a NaN 5 a NaN records.loc[:, days].interpolate(…

PEP8 for long methods name [duplicate]

This question already has an answer here:How to choose proper variable names for long names in python(1 answer)Closed 5 years ago.What is the PEP8 correct way for long methods name? I have a unit test…

POST method to upload file with json object in python flask app

I am stuck in a problem where I am trying to build single API which will upload file along with json object. I need this API to create webhook.Using multi part, I am able to upload file and in option f…

Django Logging with FileHandler not Working

I am using the logging setup below with a django project (also using sentry/raven). The sentry/raven bit is working fine, but the file logging isnt. An empty logfile is created, but whenever I use logg…

How to directly access a resource in a Py2app (or Py2exe) program?

This is mostly for Py2app, but I plan to also port to Windows so Py2exe is also applicable.For Mac: How can I access the Resources folder of my app bundle from Python code? The ideal way for me would …

Workflow for Python with Docker + IDE for non-web applications

I am currently trying to insert Docker in my Python development workflow of non-web applications.What are the current best practices in Python development using Docker and an IDE? I need the possibili…