EventGet 50% off your ticket to MongoDB.local NYC on May 2. Use code Web50!Learn more >>
MongoDB Developer
PHP
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Languageschevron-right
PHPchevron-right

Handling MongoDB PHP Errors

Hubert Nguyen7 min read • Published Jan 30, 2023 • Updated Feb 03, 2023
MongoDBPHP
Facebook Icontwitter iconlinkedin icon
Rate this article
star-empty
star-empty
star-empty
star-empty
star-empty
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.
This article was written using PHP 8.1 and MongoDB 6.1.1 (serverless) with the PHP Extension and Library 1.15. As things may change in the future, you can refer to our official MongoDB PHP documentation.

Prerequisites

To execute the code sample created for this article, you will need:
We will refer to the MongoDB PHP Driver, which has two distinct components. First, there's the MongoDB PHP Extension, which is the system-level interface to MongoDB.
Secondly, there's the MongoDB PHP Library, a PHP library that is the application's interface to MongoDB. You can learn about the people behind our PHP driver in this excellent podcast episode.

Initializing our code sample

Clone it from the Github repository to a local folder in the public section of your web server and website. You can use the command
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.
Create an .env file containing your database user credentials in the same folder as index.php. Our previous tutorial describes how to do this in the "Securing Usernames and Passwords" section. The .env file is a simple text file formatted as follows:
MDB_USER=[user name]
MDB_PASS=[password]
In your web browser, navigate to website-url/php-error-handling-sample/, and index.php  will 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.

System-level error handling

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:
  1. Is the MongoDB extension installed and loaded?
  2. 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.
  1. You can call PHP's extension_loaded() function with mongodb as the argument. It will return true or false.
  2. You can call class_exists() to check for the existence of the MongoDB\Driver\Manager class defined in the MongoDB PHP extension.
  3. Call phpversion('mongodb'), which should return the MongoDB PHP extension version number on success and false on failure.
  4. The MongoDB PHP Library also contains a detect-extension.php file which shows another way of detecting if the extension was loaded. This file is not part of the distribution but it is documented.
Failure for either means the MongoDB PHP extension has not been loaded properly and you should check your php.ini configuration and error logs, as this is a system configuration issue. Our Getting Set Up to Run PHP with MongoDB article provides debugging steps and tips which may help you.
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\Client class. If it's there, the library has been added to your project and is available at runtime.

Database instance initialization

You can now instantiate a client with your connection string . (Here's how to find the Atlas connection string.)
The instantiation will fail if something is wrong with the connection string parsing or the driver  cannot resolve the connection's SRV (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.
Up to this point, the library has just constructed an internal driver manager, and no I/O to the cluster has been performed. This behavior is described in this PHP library documentation page — see the "Behavior" section.
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.
In the MongoDB Atlas GUI sidebar, there's a "Security" section with links to the "Database Access" and "Network Access" configuration pages. "Database Access" is where you create database users and their privileges. "Network Access" lets you add IP addresses to the IP 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.

CRUD error handling

If you haven't performed CRUD operation with MongoDB before, we have a great tutorial entitled "Creating, Reading, Updating, and Deleting MongoDB Documents with PHP." Here, we'll look at the error handling mechanisms.
We will access one of the sample databases called "sample_analytics ," and read/write into the "customers" collection. If you're unfamiliar with MongoDB's terminology, here's a quick overview of the MongoDB database and collections.
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:
MongoDB CRUD operations have a multitude of legitimate reasons to encounter an exception. The general way of handling these errors is to put your operation in a try/catch block to avoid a fatal error.
If no exception is encountered, most operations return a document containing information about how the operation went.
For example, write operations return a document that contains a write concern "isAcknowledged" boolean and a WriteResult object. It has important feedback data, such as the number of matched and modified documents (among other things). Your app can check to ensure the operation performed as expected.
If an exception does happen, you can add further checks to see exactly what type of exception. For reference, look at the MongoDB exception class tree and keep in mind that you can get more information from the exception than just the message. The driver's ServerException class can also provide the exception error code, 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.
MongoDB maintains an array of tests for its PHP Library (see DocumentationExamplesTest.php on Github). It contains great code examples of various queries, with error handling. I highly recommend looking at it and using it as a reference since it will stay up to date with the latest driver and APIs.

Conclusion

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.
To learn more about using MongoDB in PHP, learn from our PHP Library tutorial, and I invite you to connect via the PHP section of our developer community forums.

References


Facebook Icontwitter iconlinkedin icon
Rate this article
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Code Example

Go-FIFA


Jul 07, 2022 | 2 min read
Tutorial

Symfony and MongoDB Workshop: Building a Rental Listing Application


Apr 08, 2024 | 3 min read
News & Announcements

Laravel MongoDB 4.2 Released, With Laravel 11 Support


Mar 20, 2024 | 1 min read
Podcast

Exploring the PHP Driver with Jeremy Mikola - Podcast Episode


May 16, 2022 | 29 min
Table of Contents