Using the error handling feature
The csql2.cpp example consists of the csql.cpp SQL
interpreter example enhanced with error-handling code. The following
steps describe the error-handling features used in the csql2.cpp example:
- Add the error callback function:
ITCallbackResult my_error_handler(const ITErrorManager &errorobject, void *userdata, long errorlevel) { // Cast the user data into a stream ostream *stream = (ostream *) userdata; (*stream) << "my_error_handler: errorlevel=" << errorlevel << " sqlstate=" << errorobject.SqlState() << ' ' << errorobject.ErrorText() << endl; return IT_NOTHANDLED; }
The arguments to the callback function are the object on which the error appeared, a field (userdata) passed to the callback function, and an indicator of the severity of the error (for details about levels of errors, see The ITErrorManager class). In this example, the callback function casts the user data field into a C++ ostream object and prints the error text and SQL error code (the ISO standard SQLSTATE) on the output stream. The user data in the example must be an ostream pointer.
- Add the callback function to the error handler list maintained
by the query object:
query.AddCallback(my_error_handler, (void *) &cerr);
The following dialog shows how the csql2.cpp program handles
an erroneous SQL statement. At the prompt (>), the user types
error;
(which
is not valid SQL) and an error message is displayed by the error handler
of the csql2.cpp program: % csql2
Connection established
> error;
my_error_handler: errorlevel=2 sqlstate=42000
X42000:-201:Syntax error or access violation
Could not execute query: error;
0 rows received, Command:
>