Error Handling with ADO

I’m new to ADO and I searched for a piece of code to handle errors,
I found the following code snippet in an article and wanted to share
it with other ADO developers that might be looking for something
similar.

The following function (LogAdoErrorImport) can be called from
any catch block in your program.


// Obtain information from the Errors Collection
HRESULT LogAdoErrorImport(_ConnectionPtr pConn)
{
  ErrorsPtr   pErrors;
  ErrorPtr    pError;
  CString     strTmp;
  HRESULT     hr = (HRESULT) 0L;
  long        nCount;

  // Don't have an un-handled exception in the handler that
  // handles exceptions!
  try
  {
     pErrors = pConn->GetErrors();

     nCount = pErrors->GetCount();

     for( long i = 0; (!FAILED(hr)) && (i < nCount); i++ )
     {
        TRACE( "t Dumping ADO Error %d of %d", i+1, nCount );

        hr = pErrors->get_Item((_variant_t)((long)i), &pError );

        _bstr_t bstrSource     ( pError->GetSource()      );
        _bstr_t bstrDescription( pError->GetDescription() );
        _bstr_t bstrHelpFile   ( pError->GetHelpFile()    );
        _bstr_t bstrSQLState   ( pError->GetSQLState()    );

        TRACE( "n Number      = %ld", pError->GetNumber()       );
        TRACE( "n Source      = %s",  (LPCTSTR) bstrSource      );
        TRACE( "n Description = %s",  (LPCTSTR) bstrDescription );
        TRACE( "n HelpFile    = %s",  (LPCTSTR) bstrHelpFile    );
        TRACE( "n HelpContext = %ld", pError->GetHelpContext()  );
        TRACE( "n SQLState    = %s",  (LPCTSTR) bstrSQLState    );
        TRACE( "n HelpContext = %ld", pError->GetHelpContext()  );
        TRACE( "n NativeError = %ld", pError->GetNativeError()  );
     }
  }
  catch( CException *e )
  {
     TRACE( "*** UNABLE TO LOG EXCEPTION ***" );
     e->Delete();
  }
  catch(...)
  {
     TRACE( "*** UNABLE TO LOG EXCEPTION ***" );
  }

  pErrors->Release();
  pError->Release();

  return hr;
}

History

More by Author

Must Read