[CXX-985] mongoCursor->next(); should return an error (as opposed to error document) Created: 09/Aug/16  Updated: 09/Aug/16  Resolved: 09/Aug/16

Status: Closed
Project: C++ Driver
Component/s: BSON
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major - P3
Reporter: Shakir Sadikali Assignee: J Rassi
Resolution: Done Votes: 0
Labels: legacy-cxx
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related

 Description   

We recently forgot to add the necessary permissions for a user, whereupon something interesting happened:

A call to mongo::DBClientBase::query() returned with a DBClientCursor, as expected, but the following code then failed because one of our field check reported a missing field that was expected in the BSONObj we expected after getting the first object.
Pseudocode:

while(mongoCursor->more())
{
  mongo::BSONObj o = mongoCursor->next();
  OurObject result;
  BsonToObject(o, result);
}

Looking into it we finally discovered that the BSONObj returned by mongoCursor->next() was not one from the collection in question, but an Error Object:

{ $err: "not authorized for query on commDB.devicedata", code: 13 }

getLastError() did not return anything, though - and we wonder now why there was no exception thrown, as it's impossible to detect the error state and avoid attempting the conversion, it seems.



 Comments   
Comment by J Rassi [ 09/Aug/16 ]

Hi,

This is expected behavior for the legacy C++ driver. You're probably interested in using DBClientCursor::nextSafe() instead of DBClientCursor::next(). See the relevant method documentation from dbclientcursor.h:

    /** next
       @return next object in the result cursor.
       on an error at the remote server, you will get back:
         { $err: <string> }
       if you do not want to handle that yourself, call nextSafe().
       Warning: The returned BSONObj will become invalid after the next batch
           is fetched or when this cursor is destroyed.
    */
    BSONObj next();

    /** throws AssertionException if get back { $err : ... } */
    BSONObj nextSafe();

Note that the new C++11 driver provides a simpler and more intuitive interface for iterating cursors (the cursor::iterator class will throw exception::query during iteration if there is an error). Do consider upgrading if possible, for an easier development experience.

~ Rassi

Generated at Wed Feb 07 22:01:00 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.