Is it possible to catch PostgreSQL output error messages in OGR after a query has failed?

For example

conn.ExecuteSQL('SELECT * FROM non_existing_table;')

In Postgres this returns an error message:

"Error: relation 'non_existing_table' does not exist."

In ogr we get the standard:

"Error: current transaction is aborted, commands ignored until end of transaction block"

It would be a bonus if we could catch/parse the Postgres error message. I suspect this is a bit of a long-shot given what I've read about SWIG/CPL, but worth asking to see if anyone's got ideas. Ideally this would be in Python, but I'll take C/C++ comments as well!


2 Answers 2


You should upgrade to GDAL/OGR 1.9.x where the error reporting for PostgreSQL datasource has been improved :

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from osgeo import ogr
>>> ogr.UseExceptions()
>>> ds = ogr.Open('pg:dbname=autotest')
>>> ds.ExecuteSQL("SELECT * FROM non_existing_table")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/dist-packages/osgeo/ogr.py", line 699, in ExecuteSQL
    return _ogr.DataSource_ExecuteSQL(self, *args, **kwargs)
RuntimeError: ERREUR:  la relation « non_existing_table » n'existe pas
LINE 1: DECLARE executeSQLCursor CURSOR for SELECT * FROM non_existi...

if you are using psycopg2, you can easily print your error message with putting it into "try" function as the following code. the code was taken from zetcode.com for not writing again...

# -*- coding: utf-8 -*-

import psycopg2
import sys

con = None


    con = psycopg2.connect(database='testdb', user='janbodnar') 
    cur = con.cursor()
    cur.execute('SELECT version()')          
    ver = cur.fetchone()
    print ver    

except psycopg2.DatabaseError, e:
    print 'Error %s' % e    


    if con:

i hope it helps you...

  • Thanks Aragon, yes Psycopg2 is a great library, but interested to see if something similar is possible via ogr. We need ogr to handle geometry operations and I'd rather not duplicate connections just for the sake of using a different API.
    – Tomas
    Jul 31, 2012 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.