@@ -183,6 +183,16 @@ CommandResult doAuthenticate(MongoCredential credentials) {
183183 return _connector .authenticate (credentials );
184184 }
185185
186+ private static void throwOnQueryFailure (final Response res , final long cursor ) {
187+ if ((res ._flags & Bytes .RESULTFLAG_ERRSET ) > 0 ) {
188+ BSONObject errorDocument = res .get (0 );
189+ throw new MongoException (ServerError .getCode (errorDocument ), ServerError .getMsg (errorDocument , null ));
190+ }
191+ else if ((res ._flags & Bytes .RESULTFLAG_CURSORNOTFOUND ) > 0 ) {
192+ throw new MongoException .CursorNotFound (cursor , res .serverUsed ());
193+ }
194+ }
195+
186196 class MyCollection extends DBCollection {
187197 MyCollection ( String name ){
188198 super ( DBApiLayer .this , name );
@@ -290,12 +300,7 @@ Iterator<DBObject> __find( DBObject ref , DBObject fields , int numToSkip , int
290300
291301 Response res = _connector .call ( _db , this , query , null , 2 , readPref , decoder );
292302
293- if ( res .size () == 1 ){
294- BSONObject foo = res .get (0 );
295- MongoException e = MongoException .parse ( foo );
296- if ( e != null && ! _name .equals ( "$cmd" ) )
297- throw e ;
298- }
303+ throwOnQueryFailure (res , 0 );
299304
300305 return new Result ( this , res , batchSize , limit , options , decoder );
301306 }
@@ -362,9 +367,7 @@ class Result implements Iterator<DBObject> {
362367 }
363368
364369 private void init ( Response res ){
365- if ( ( res ._flags & Bytes .RESULTFLAG_CURSORNOTFOUND ) > 0 ){
366- throw new MongoException .CursorNotFound (_curResult .cursor (), res .serverUsed ());
367- }
370+ throwOnQueryFailure (res , _curResult == null ? 0 : _curResult ._cursor );
368371
369372 _totalBytes += res ._len ;
370373 _curResult = res ;
0 commit comments