I am creating an application with QGIS libraries, and in the event that the app can't add a specified layer (e.g. no connection to host, no password specified etc), it causes the app to crash, although I do get some output in the console, like QGIS displays in a message box:
credentials for dbname='testdb' host=testserver port=5432 message: fe_sendauth: no password supplied
This seems to be returned at the point where I create my
QgsVectorLayer instance because the app becomes unresponsive and doesn't progress further.
My script to load the layer:
def add_postgis_vector_layer(self, username, password, layer_name, label, geometry, id): uri = core.QgsDataSourceURI() uri.setConnection(HOST, PORT, DATABASE, username, password) uri.setDataSource(SCHEMA, layer_name, geometry, '', id) layer = core.QgsVectorLayer(uri.uri(), label, 'postgres', False) # Error message occurs at this point if layer.isValid(): self.canvas.setExtent(layer.extent()) self.canvas.zoomScale(self.canvas.scale() * 1.1) self.canvas.setWheelAction(2) # Set canvas map layers layers = [gui.QgsMapCanvasLayer(layer)] self.canvas.setLayerSet(layers)
The QApplication subclass:
class myApplication(QtGui.QApplication): def __init__(self, args): super(myApplication, self).__init__(args) core.QgsApplication.setPrefixPath(qgis_prefix, True) core.QgsApplication.initQgis()
How do I access this connection error? I can't call
layer.error() (not sure if this would even work) because the app has crashed already and won't process any more code.
I'm thinking I could avoid the error by performing a query using
psycopg2 with the parameters I am about to use. Still doesn't address the issue of retrieving any errors in the connection.