Error Handling in C
Textual error messages associated with each error number can be retrieved using the SQL statement GET DIAGNOSTICS and GET DIAGNOSTICS EXCEPTION. These can be declared in a function which is called in the event of a non-zero SQLCODE being returned.
The C program must declare a character variable to receive the error text, an integer variable containing the length of the error text, an integer variable containing the total number of error conditions available and an integer variable containing the current error condition. These 4 items must be declared in a DECLARE SECTION which is in scope whenever the above SQL statements are called.
A programming example using GET DIAGNOSTICS / GET DIAGNOSTICS EXCEPTION looks like this:
/* --------------------------------------------------- */
void doERROR()
{
EXEC SQL BEGIN DECLARE SECTION;
char errBuf[ 513 ]; /* Error Text Buffer */
int errLen = 513; /* Length of Error Text Buffer */
int conditionCount; /* Count of error conditions */
int errNumber; /* Current error condition */
EXEC SQL END DECLARE SECTION;
/* Obtain the count of error conditions to be returned in conditionCount */
EXEC SQL
GET DIAGNOSTICS :conditionCount = NUMBER;
/* Obtain each error condition text conditionCount times */
/* The error condition text will be returned in errBuf */
for( errNumber = 1;
errNumber <= conditionCount;
errNumber++)
{
EXEC SQL
GET DIAGNOSTICS EXCEPTION :errNumber
:errBuf = MESSAGE_TEXT,
:errLen = MESSAGE_LENGTH;
printf( "ERR MSG: %s\n\n", errBuf );
}
}
where
conditionCount | is the count of error conditions available, returned by GET DIAGNOSTICS. |
errNumber | is the current error condition. |
errBuf | is the target buffer, null-terminated on return from GET DIAGNOSTICS EXCEPTION. |
errLen | is the length of the target buffer errBuf. |