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.

.. code-block:: c

    mongo conn[1];

    if ( mongo_client( 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 <api/mongo_8h.html#a5e6f76bd796c89973ffb463e676237bb>`_ to interpret this.

Next, we print the OS-level error code. On POSIX-compliant systems, this will be the value of
`errno <http://pubs.opengroup.org/onlinepubs/009695399/functions/errno.html>`_; 
on Windows, it's the value of `WSAGetLastError() <http://msdn.microsoft.com/en-us/library/ms898741.aspx>`_.

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() <http://pubs.opengroup.org/onlinepubs/009604499/functions/strerror.html>`_), 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:

.. code-block:: c

    mongo conn[1];
    int res;

    if( mongo_client( 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:

.. code-block:: c

    mongo_clear_errors( conn );
