Rate this article
Welcome to this article about MongoDB error handling in PHP. Code samples and tutorials abound on the web , but for clarity's sake, they often don't show what to do with potential errors. Our goal here is to show you common mechanisms to deal with potential issues like connection loss, temporary inability to read/write, initialization failures, and more.
Go to the project's directory with the command
and run the command
Composer will download external libraries to the "vendor" directory (see the screenshot below). Note that Composer will check if the MongoDB PHP extension is installed, and will report an error if it is not.
In your web browser, navigate to
index.phpwill be executed.
Upon execution, our code sample outputs a page like this, and there are various ways to induce errors to see how the various checks work by commenting/uncommenting lines in the source code.
Initially, developers run into system-level issues related to the PHP configuration and whether or not the MongoDB PHP driver is properly installed. That's especially true when your code is deployed on servers you don't control. Here are two common system-level runtime errors and how to check for them:
- Is the MongoDB extension installed and loaded?
- Is the MongoDB PHP Library available to your code?
There are many ways to check if the MongoDB PHP extension is installed and loaded and here are two in the article, while the others are in the the code file.
- You can call PHP's
mongodbas the argument. It will return true or false.
- You can call
class_exists()to check for the existence of the
MongoDB\Driver\Managerclass defined in the MongoDB PHP extension.
phpversion('mongodb'), which should return the MongoDB PHP extension version number on success and false on failure.
Once the MongoDB PHP extension is up and running, the next thing to do is to check if the MongoDB PHP Library is available to your code. You are not obligated to use the library, but we highly recommend you do. It keeps things more abstract, so you focus on your app instead of the inner-workings of MongoDB.
Look for the
MongoDB\Clientclass. If it's there, the library has been added to your project and is available at runtime.
The instantiation will fail if something is wrong with the connection string parsing or the driver cannot resolve the connection's (DNS) record. Possible causes for SRV resolution failures include the IP address being rejected by the MongoDB cluster or network connection issues while checking the SRV.
It's important to know that even though the client was successfully instantiated, it does not mean your user/password pair is valid , and it doesn't automatically grant you access to anything . Your code has yet to try accessing any information, so your authentication has not been verified.
When you first create a MongoDB Atlas cluster, there's a "Connect" button in the GUI to retrieve the instance's URL. If no user database exists, you will be prompted to add one, and add an IP address to the access list.
Next, you can do a first operation that requires an I/O connection and an authentication, such as listing the databases with
listDatabaseNames(), as shown in the code block below. If it succeeds, your user/password pair is valid. If it fails, it could be that the pair is invalid or the user does not have the proper privileges.
There are other reasons why any MongoDB command could fail (connectivity loss, etc.), and the exception message will reveal that. These first initialization steps are common points of friction as cluster URLs vary from project to project, IPs change, and passwords are reset.
Sometimes, ensuring the connected cluster contains the expected database(s) and collection(s) might be a good idea. In our code sample, we can check as follows:
If no exception is encountered, most operations return a document containing information about how the operation went.
If an exception does happen, you can add further checks to see exactly what type of exception. For reference, look at the and keep in mind that you can get more information from the exception than just the message. The driver's can also provide the exception , the source code line and the trace, and more!
For example, a common exception occurs when the application tries to insert a new document with an existing unique ID. This could happen for many reasons, including in high concurrency situations where multiple threads or clients might attempt to create identical records.
This article was intended to introduce MongoDB error handling in PHP by highlighting common pitfalls and frequently asked questions we answer. Understanding the various MongoDB error-handling mechanisms will make your application rock-solid, simplify your development workflow, and ultimately make you and your team more productive.