PHP & MongoDB - Error Handling



Syntax

MongoDB driver operations throws exceptions in case of any database operations and can be captured easily using following syntax:

try {

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

Example - Handling Database Error

Try the following example to check Database error while trying to connect to a MongoDB database using invalid port −

index.php

<?php
   require __DIR__ . '\vendor\autoload.php';
   $uri = "mongodb://localhost:27020";
   try {
      // connect to mongodb
      $client = new MongoDB\Client($uri);
   
      // select a database
      $db = $client->myDb;

      // execute a command
      $cursor=$db->command(array('create' => 'sampleCollection'));
      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

Access the index.php deployed on apache web server and verify the output.

Exception:No suitable servers found (`serverSelectionTryOnce` set): [connection refused calling hello on 'localhost:27020']. Topology type: Single
File:D:\Apache\Apache24\htdocs\php\vendor\mongodb\mongodb\src\functions.php
Line:600
Advertisements