Exceptions

Table of Contents

VMWare Oddities

If you are running VMWare on Windows and are using CIFS, pausing the VM will cause CIFS to go out of sync and cause weird errors on un-pausing it ("The Mongo object has not been correctly initialized by its constructor"). Permanently mounting the Windows shares will fix this and you'll be able to pause and unpause at will.

To permanently mount the Windows shares, run:

$ sudo update-rc.d -f umountnfs.sh remove
$ sudo update-rc.d umountnfs.sh stop 15 0 6 .

See » the Ubuntu docs for the most up-to-date instructions.

The MongoException class

Introduction

Default Mongo exception.

This covers a bunch of different error conditions that may eventually be moved to more specific exceptions, but will always extend MongoException.

  • The MongoSomething object has not been correctly initialized by its constructor

    Code: 0

    Probably your Mongo object is not connected to a database server.

  • zero-length keys are not allowed, did you use $ with double quotes?

    Code: 1

    You tried to save "" as a key. You generally should not do this. "" can mess up subobject access and is used by MongoDB internally. However, if you really want, you can set mongo.allow_empty_keys to true in your php.ini file to override this sanity check. If you override this, it is highly recommended that you set error checking to strict to avoid string interpolation errors.

  • '.' not allowed in key: <key>

    Code: 2

    You attempted to write a key with '.' in it, which is prohibited.

  • insert too large: <size>, max: <max>

    Code: 3

    You're attempting to send too much data to the database at once: the database will only accept inserts up to a certain size (currently 16 MB).

  • no elements in doc

    Code: 4

    You're attempting to save a document with no fields.

  • size of BSON doc is <size> bytes, max <max>MB

    Code: 5

    You're attempting to save a document that is larger than MongoDB can save.

  • no documents given

    Code: 6

    You're attempting to batch insert an empty array of documents.

  • MongoCollection::group takes an array, object, or MongoCode key

    Code: 7

    Wrong type parameter send to MongoCollection::group.

  • field names must be strings

    Code: 8

    You should format field selectors as array("field1" => 1, "field2" => 1, ..., "fieldN" => 1).

  • invalid regex

    Code: 9

    The regex passed to MongoRegex is not of the correct form.

  • MongoDBRef::get: $ref field must be a string

    Code: 10

  • MongoDBRef::get: $db field must be a string

    Code: 11

  • non-utf8 string: <str>

    Code: 12

    This error occurs if you attempt to send a non-utf8 string to the database. All strings going into the database should be UTF8. See php.ini options for the transition option of quieting this exception.

  • mutex error: <err>

    Code: 13

    The driver uses mutexes for synchronizing requests and responses in multithreaded environments. This is a fairly serious error and may not have a stack trace. It's unusual and should be reported to maintainers with any system information and steps to reproduce that you can provide.

  • index name too long: <len>, max <max> characters

    Code: 14

    Indexes with names longer than 128 characters cannot be created. If you get this error, you should use MongoCollection::ensureIndex's "name" option to create a shorter name for your index.

Class synopsis

MongoException
class MongoException extends Exception {
}

The MongoResultException class

Introduction

The MongoResultException is thrown by several command helpers (such as MongoCollection::findAndModify) in the event of failure. The original result document is available through MongoResultException::getDocument.

Class synopsis

MongoResultException
class MongoResultException extends MongoException {
/* Properties */
public $document ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public array getDocument ( void )
}

Properties

document

The raw result document as an array.

The MongoCursorException class

Introduction

Caused by accessing a cursor incorrectly or a error receiving a reply. Note that this can be thrown by any database request that receives a reply, not just queries. Writes, commands, and any other operation that sends information to the database and waits for a response can throw a MongoCursorException. The only exception is new MongoClient() (creating a new connection), which will only throw MongoConnectionExceptions.

This returns a specific error message to help diagnose the problem and a numeric error code associated with the cause of the exception.

For example, suppose you tried to insert two documents with the same _id:

<?php

try {
    
$collection->insert(array("_id" => 1), array("w" => 1));
    
$collection->insert(array("_id" => 1), array("w" => 1));
}
catch (
MongoCursorException $e) {
    echo 
"error message: ".$e->getMessage()."\n";
    echo 
"error code: ".$e->getCode()."\n";
}

?>
This would produce output like:
error message: E11000 duplicate key error index: foo.bar.$_id_  dup key: { : 1 }
error code: 11000
Note that the MongoDB error code (11000) is used for the PHP error code. The PHP driver uses the "native" error code wherever possible.

The following is a list of common errors, codes, and causes. Exact errors are in italics, errors where the message can vary are described in obliques.

  • cannot modify cursor after beginning iteration

    Code: 0

    You are calling a method that sets up the query after executing the query. Reset the cursor and try again.

    An example:

    <?php

    try {
        
    $cursor $collection->find();
        
    var_dump($cursor->getNext());

        
    // getNext() queried the database, it's too late to set a limit
        
    $cursor->limit(1);
    }
    catch (
    MongoCursorException $e) {
        echo 
    "error message: ".$e->getMessage()."\n";
        echo 
    "error code: ".$e->getCode()."\n";
    }

    // this will work, though:
    $cursor->getNext();
    $cursor->reset();
    $cursor->limit(1);

    ?>

  • Get next batch send errors

    Code: 1

    Could not send the query to the database. Make sure the database is still up and the network is okay.

  • cursor not found

    Code: 2

    The driver was trying to fetch more results from the database, but the database did not have a record of the query. This usually means that the cursor timed out on the server side: after a few minutes of inactivity, the database will kill a cursor (see MongoCursor::immortal for information on preventing this).

    An example:

    <?php

    try {
        
    $cursor $collection->find();
        
    $cursor->getNext();

        
    // sleep for 15 minutes
        
    sleep(60*15);

        while (
    $cursor->hasNext()) {
            
    $cursor->getNext();
        }
    }
    catch (
    MongoCursorException $e) {
        echo 
    "error message: ".$e->getMessage()."\n";
        echo 
    "error code: ".$e->getCode()."\n";
    }

    ?>

  • cursor->buf.pos is null

    Code: 3

    This may indicate you are out of RAM or some other extraordinary circumstance.

  • couldn't get response header

    Code: 4

    A common error if the database or network goes down. This means that the driver couldn't get a response from the connection.

  • no db response

    Code: 5

    This may not even be an error, for example, the database command "shutdown" returns no response. However, if you were expecting a response, this means the database didn't give one.

  • bad response length: %d, did the db assert?

    Code: 6

    This means that the database said that its response was less than 0. This error probably indicates a network error or database corruption.

  • incomplete header

    Code: 7

    Highly unusual. Occurs if the database response started out correctly, but broke off in the middle. Probably indicates a network problem.

  • incomplete response

    Code: 8

    Highly unusual. Occurs if the database response started out correctly, but broke off in the middle. Probably indicates a network problem.

  • couldn't find a response

    Code: 9

    If the response was cached and now cannot be located.

  • error getting socket

    Code: 10

    The socket was closed or encountered an error. The driver should automatically reconnect (if possible) on the next operation.

  • couldn't find reply, please try again

    Code: 11

    The driver saves any database responses it cannot immediately match with a request. This exception occurs if the driver has already passed your request's response and cannot find your response in its cache.

  • error getting database response: errstr

    WSA error getting database response: errstr

    "errstr" is an io error reported directly from the C socket subsystem. On Windows, the error message is prefixed with "WSA".

  • Timeout error

    Code: 13

    If there was an error while waiting for a query to complete.

  • couldn't send query: <various>

    Code: 14

    C socket error on send.

  • max number of retries exhausted, couldn't send query

    Code: 19

    The driver will automatically retry "plain" queries (not commands) a couple of times if the first attempt failed for certain reasons. This is to cause fewer exceptions during replica set failover (although you will probably still have to deal with some) and gloss over transient network issues.

    This can also be caused by the driver not being able to reconnect at all to the database (if, for example, the database is unreachable).

    Version 1.2.2+.

Errors passed through by the database

Database errors should always trigger MongoCursorExceptions on queries. Error messages and codes are sent directly from the database and you should be able to see matching errors in the database log.

A few common database errors are listed below:

  • E11000 duplicate key error index: foo.bar.$X dup key: { /* ... */ }

    Code: 11000

    Database error for duplicate keys.

  • not master

    Codes: 10107, 13435, and 10058

    Not master errors, piped through by the database. ach of these will cause the driver to disconnect and attempt to find a new primary. The actual error you get on failover may not be a "not master" error, depending on when the change in primary occurs.

Class synopsis

MongoCursorException
class MongoCursorException extends MongoException {
}

The MongoCursorTimeoutException class

Introduction

Caused by a query timing out. You can set the length of time to wait before this exception is thrown by calling MongoCursor::timeout on the cursor or setting MongoCursor::$timeout. The static variable is useful for queries such as database commands and MongoCollection::findOne, both of which implicitly use cursors.

Class synopsis

MongoCursorTimeoutException
class MongoCursorTimeoutException extends MongoCursorException {
}

The MongoConnectionException class

Introduction

Thrown when the driver fails to connect to the database.

There are a number of possible error messages to help you diagnose the connection problem. These are:

  • No candidate servers found

    Thrown when the driver cannot establish a connection to MongoDB (fulfilling the ReadPreferences, if specified).

  • No server name given.

    This error occurs if you pass in "" as the server name, probably because of an typo with string interpolation, e.g., "$servr" instead of "$server".

  • failed to get host [hostname] or port [portnum] from [server].

    This indicated that the server string was malformed. "[hostname]" and "[portnum]" will be as much as the driver could dicipher of it.

  • Operation in progress

    Connecting to the database timed out.

  • Transport endpoint is not connected

    Generally means that the connection string isn't correct, the driver couldn't even find the database server.

  • couldn't determine master

    No server in a replica set connection was identified as the primary.

  • couldn't get host info for [server]

    This indicated that DNS could not resolve the server address you gave. This could easily be caused by a typo, for example, "server" instead of "$server".

  • Invalid Argument

    This can be caused by attempting to connect to a machine that is up but that the database isn't actually running on. Make sure that you've started the database server before connecting.

  • Permission denied

    This means that the socket could not be opened due to permissions issues. On Red Hat variants, this can be caused by a default setting that does not allow Apache to create network connections. You can override this setting by running:

    $ /usr/sbin/setsebool -P httpd_can_network_connect 1
    then restarting Apache.

If the error message is not listed above, it is probably an error from the C socket, and you can search the web for its usual cause.

Class synopsis

MongoConnectionException
class MongoConnectionException extends MongoException {
}

The MongoGridFSException class

Introduction

Thrown when there are errors reading or writing files to or from the database.

Class synopsis

MongoGridFSException
class MongoGridFSException extends MongoException {
}

Error codes

MongoGridFSException error codes
Code Message Reason
3 Could not open file $filename Attempting to store an invalid file, such as directory
4 File $filename is too large: $filesize bytes Maximum filesize in GridFS is 4GB
5 could not find filehandle Resource doesn't have a filehandle
6 no file is associate with this filehandle Resource isn't a file resource
7 error setting up file: $filenames Could not open file for reading
9 error reading file $filenames Failed reading file
10 error reading filehandle Failed reading from a resource
11 could not find uploaded file %s Filename doesn't seem to be uploaded file
12 Couldn't find tmp_name in the $_FILES array. Are you sure the upload worked? Uploaded filename probably failed
13 tmp_name was not a string or an array Invalid filename given
14 couldn't find file size The length property is missing
15 Cannot find filename No filename provided, and no filename property set
16 could not open destination file %s Destination filename not writable
17 error reading chunk of file Chunk corruption
18 couldn't create a php_stream Couldn't create a stream resource
19 couldn't find property Chunk corruption
20 chunk number has wrong size (size) when the max is maxchunksize Chunk larger then expected
21 chunk has wrong format Chunk corruption

The MongoDuplicateKeyException class

Introduction

Thrown when attempting to insert a document into a collection which already contains the same values for the unique keys.

Class synopsis

MongoDuplicateKeyException
class MongoDuplicateKeyException extends MongoWriteConcernException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
public array MongoWriteConcernException::getDocument ( void )
}

Examples

Example #1 Catching MongoDuplicateKeyException

<?php
$mc 
= new MongoClient("localhost");

$c $mc->selectCollection("test""test");

$c->insert(array('_id' => 1));
try {
    
$c->insert(array('_id' => 1));
} catch (
MongoWriteConcernException $e) {
    echo 
$e->getMessage(), "\n";
}
?>

The above examples will output something similar to:

localhost:27017: insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.test.$_id_  dup key: { : 1 }

The MongoProtocolException class

Introduction

When talking to MongoDB 2.6.0, and later, certain operations (such as writes) may throw MongoProtocolException when the response from the server did not make sense - for example during network failure (we could read the entire response) or data corruption.

This exception is also thrown when attempting to talk newer protocols then the server supports, for example using the MongoWriteBatch when talking to a MongoDB server prior to 2.6.0.

Class synopsis

MongoProtocolException
class MongoProtocolException extends MongoException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}

Examples

Example #2 Catching MongoProtocolException

Running the following example against MongoDB prior to 2.6.0 will throw an MongoProtocolException

<?php
$mc 
= new MongoClient("localhost");
$c $mc->selectCollection("test""test");

try {
    
$batch = new MongoInsertBatch($c);
} catch(
MongoProtocolException $e) {
    echo 
$e->getMessage();
}
?>

The above examples will output something similar to:

Current primary does not have a Write API

The MongoExecutionTimeoutException class

Introduction

Thrown when a operation times out server side (i.e. in MongoDB).

To configure the operation timeout threshold, use MongoCursor::maxTimeMS or the "maxTimeMS" command option.

Class synopsis

MongoExecutionTimeoutException
class MongoExecutionTimeoutException extends MongoException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}

The MongoWriteConcernException class

Introduction

MongoWriteConcernException is thrown when a write fails. See Write Concerns for how to set failure thresholds.

Prior to MongoDB 2.6.0, the » getLastError command would determine whether a write failed.

Class synopsis

MongoWriteConcernException
class MongoWriteConcernException extends MongoCursorException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public array getDocument ( void )
/* Inherited methods */
public string MongoCursorException::getHost ( void )
}