Php Mongodb 简明教程

PHP & MongoDB - Error Handling

MongoDB 驱动器操作会抛出数据库操作异常,并且可以使用以下语法轻松地捕获这些异常:

try {

} catch (MongoDB\Driver\Exception\Exception $e) {
   echo "Exception:", $e->getMessage(), "<br/>";
   echo "File:", $e->getFile(), "<br/>";
   echo "Line:", $e->getLine(), "<br/>";
}

Example

尝试以下示例以检查 MongoDB 服务器中的数据库操作错误 −

将以下示例复制粘贴到 mongodb_example.php −

<?php
   try {
	  // connect to mongodb
      $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

      // Create a Command Instance
      $createCollection = new MongoDB\Driver\Command(["create" => "sampleCollection"]);

      // Execute the command on the database
      $cursor = $manager->executeCommand("myDb", $createCollection);

      echo "Collection created.";
   } catch (MongoDB\Driver\Exception\Exception $e) {
      echo "Exception:", $e->getMessage(), "<br/>";
      echo "File:", $e->getFile(), "<br/>";
      echo "Line:", $e->getLine(), "<br/>";
   }
?>

Output

访问部署在 Apache Web 服务器上的 mongodb_example.php 并验证输出。

Exception:Collection already exists. NS: myDb.sampleCollection
File: \htdocs\php_mongodb\mongodb_example.php
Line:10