psycopg2.Error isn't being caught in python try/except block

Viewed 1115

I am developing an application using django with a PostgreSQL database. The application is designed to be used within an organization, so user-supplied SQL requests need to be executed. To deal with the possibility of malformed SQL requests, the database calls are wrapped in a try/except block:

import psycopg2
...
def djangoView(request):
    ...
    try:
        result = DBModel.objects.raw(sqlQuery)
        return getJSONResponse(result) #Serializes result of query to JSON
    except psycopg2.Error:
        pass #Handle error (no db requests are made)

However, when I make a request to the view with malformed SQL, I am greeted with a 500 internal server error. The stack trace reveals that the cause of the 500 is a ProgrammingError, which is a subclass of psycopg2.Error. However, the except statement doesn't catch it correctly.

1 Answers
Related