Client 2 - Adding Error Checking

Now let's add a little error-handling code to the client:

/* client2a.c   */

#include <stdlib.h>

#include <libpq-fe.h>

#include <libpgeasy.h>

int main( int argc, char * argv[] )


  PGconn *  connection;

  connection = connectdb( argv[1] ? argv[1] : "" );

  if( PQstatus( connection ) != CONNECTION_OK )

    printf( "Caught an error: %s\n", PQerrorMessage( connection ));


    printf( "connection ok\n" );


  exit( EXIT_SUCCESS );


This time around, I captured the PGconn * returned by connectdb(). Remember that this PGconn * is the same type of object that you would find in a libpq application. Call the PQstatus() function to determine whether the connection attempt succeeded or failed. If a failure occurs, print an error message; otherwise, print "connection ok."

Let's run this a couple of times to see how it behaves:

$ ./client2a dbname=movies

connection ok

As expected, you see a friendly little confirmation that the connection attempt was successful. Now let's feed in an error and see what happens:

$ ./client2a dbname=foofoo

Connection to database using 'dbname=foofoo' failed.

FATAL 1:  Database "foofoo" does not exist in the system catalog.

This time, you see an error message. But look closely and you'll see that the error message doesn't match your source code?the error message should start with the text Caught an error:.

What happened? If you don't make any other arrangements, connectdb() will print an error message and terminate the calling program if it encounters a failure. So, this program didn't even get to the point where it could call PQstatus()?the program terminated before connectdb() ever returned.

So, how do you make these "other arrangements?" libpgeasy provides two functions that you can use to control the error-handling mode:

void on_error_stop( void );

void on_error_continue( void );

The on_error_stop() function tells libpgeasy that you want it to handle error conditions. Calling on_error_continue() tells libpgeasy that you want to handle error conditions yourself. on_error_stop() is the default error-handling mode.

I should point out here that calling on_error_continue() has no effect on the connectdb() function. If the connection attempt fails, connectdb() will terminate the program regardless of which error-handling mode is in effect.

In the next section, you will see that libpgeasy does in fact let you construct your own error-handling code once a connection has been established.

    Part II: Programming with PostgreSQL