Преглед изворни кода

Add exceptions to MongoCursor

Olivier Lechevalier пре 10 година
родитељ
комит
9af920fe5f
2 измењених фајлова са 25 додато и 2 уклоњено
  1. 15 2
      lib/Mongo/MongoCursor.php
  2. 10 0
      tests/Alcaeus/MongoDbAdapter/MongoCursorTest.php

+ 15 - 2
lib/Mongo/MongoCursor.php

@@ -15,6 +15,7 @@
 
 use Alcaeus\MongoDbAdapter\AbstractCursor;
 use Alcaeus\MongoDbAdapter\TypeConverter;
+use Alcaeus\MongoDbAdapter\ExceptionConverter;
 use MongoDB\Driver\Cursor;
 use MongoDB\Driver\ReadPreference;
 use MongoDB\Operation\Find;
@@ -140,8 +141,14 @@ class MongoCursor extends AbstractCursor implements Iterator
         }
 
         $options = $this->getOptions($optionNames) + $this->options;
+        try {
+            $count = $this->collection->count(TypeConverter::fromLegacy($this->query), $options);
+        } catch (\MongoDB\Driver\Exception\ExecutionTimeoutException $e) {
+            throw new MongoCursorTimeoutException($e->getMessage(), $e->getCode(), $e);
+        } catch (\MongoDB\Driver\Exception\Exception $e) {
+            ExceptionConverter::toLegacy($e);
+        }
 
-        $count = $this->collection->count(TypeConverter::fromLegacy($this->query), $options);
         return $count;
     }
 
@@ -155,7 +162,13 @@ class MongoCursor extends AbstractCursor implements Iterator
     {
         $options = $this->getOptions() + $this->options;
 
-        $this->cursor = $this->collection->find(TypeConverter::fromLegacy($this->query), $options);
+        try {
+            $this->cursor = $this->collection->find(TypeConverter::fromLegacy($this->query), $options);
+        } catch (\MongoDB\Driver\Exception\ExecutionTimeoutException $e) {
+            throw new MongoCursorTimeoutException($e->getMessage(), $e->getCode(), $e);
+        } catch (\MongoDB\Driver\Exception\Exception $e) {
+            ExceptionConverter::toLegacy($e);
+        }
     }
 
     /**

+ 10 - 0
tests/Alcaeus/MongoDbAdapter/MongoCursorTest.php

@@ -39,6 +39,16 @@ class MongoCursorTest extends TestCase
         $this->assertSame(1, $cursor->count(true));
     }
 
+    public function testCountCannotConnect()
+    {
+        $client = $this->getClient([], 'mongodb://localhost:28888');
+        $cursor = $client->selectCollection('mongo-php-adapter', 'test')->find();
+
+        $this->setExpectedException('MongoConnectionException');
+
+        $cursor->count();
+    }
+
     /**
      * @dataProvider getCursorOptions
      */