A
A
Anton2021-02-27 11:07:39
Django
Anton, 2021-02-27 11:07:39

How to catch an exception in Django that the framework replaces with its own?

I need to catch the psycopg2.errors.UndefinedColumn exception that is thrown when trying to run a query:

from django.db import connection

with connection.cursor() as cursor:
    try:
        cursor.execute(query, params)
    except UndefinedColumn:
        ...

But it is processed by Django, and already returns django.db.utils.ProgrammingError.
psycopg2.errors.UndefinedColumn: column "col" does not exist
The above exception was the direct cause of the following exception:
django.db.utils.ProgrammingError: column "col" does not exist

Is there a way to get to the original exception from psycopg2?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-02-27
@Gambetto

The Django wrappers for database exceptions behave exactly the same as the underlying database exceptions. See PEP 249, the Python Database API Specification v2.0, for further information.
As per PEP 3134, a __cause__ attribute is set with the original (underlying) database exception, allowing access to any additional information provided.
https://docs.djangoproject.com/en/3.1/ref/exceptio...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question