Error Reporting

The MongoDB C driver reports errors from three sources:

  • The operating system
  • The MongoDB server
  • The driver itself -- typically user input errors

The driver's API is structured such that nearly all functions return either MONGO_OK or MONGO_ERROR. When a function returns MONGO_ERROR, you may examine the mongo object to see why the error has occurred.

Operating system errors

A good example of an operating system error is a connection failure.

mongo conn[1];

if ( mongo_connect( conn, "foo.example.com", 27017 ) == MONGO_ERROR ) {
    printf( "mongo_error_t: %d\n", conn->err );
    printf( "errno (or WSAGetLastError() on Windows: %d\n", conn->errcode );
    printf( "Error string: %s\n", conn->errstr );
    exit( 1 );
}

First, we print the mongo_error_t to get the general error type. Consult the mongo_error_t definition to interpret this.

Next, we print the OS-level error code. On POSIX-compliant systems, this will be the value of errno; on Windows, it's the value of WSAGetLastError().

Finally, we print the error string, which gives is a few more details. This string may be the OS-level translation of the error code (e.g., POSIX's strerror()), or it may be a string generated by the driver itself which better describes the failure.

MongoDB errors

MongoDB itself produces errors that may be returned to the client after any query or call to the getlasterror command. The code and strings for these errors are stored in the mongo object's lasterrcode and lasterrstring, respectively. We can force this sort of error by trying to run an invalid command:

mongo conn[1];
int res;

if( mongo_connect( conn, "foo.example.com", 27017 ) == MONGO_ERROR ) {
    exit( 1 );
}

if( mongo_simple_int_command( conn, "admin", "badCommand", 1, &out ) == MONGO_ERROR ) {
    printf("Last error code: %d\n", conn->lasterrcode );
    printf("Last error string: %s\n", conn->lasterrstr );
}

Clearing errors

To reset errors on the mongo object, run the mongo_clear_errors function:

mongo_clear_errors( conn );