-
Notifications
You must be signed in to change notification settings - Fork 268
Description
In the new library and/or driver if you try to insert a document which results in a duplicate key error then you get the following exception:
object(MongoDB\Driver\Exception\BulkWriteException)#824 (8) {
["message":protected]=> string(96) "E11000 duplicate key error collection: app.exchangeRates index: _id_ dup key: { : "2016-10-05" }"
["string":"Exception":private]=> string(0) ""
["code":protected]=> int(0)
["file":protected]=> string(81) ".../mongo-php-library-1.0.2/src/Operation/InsertOne.php"
["line":protected]=> int(86)
["trace":"Exception":private]=> array(16) { ... }
}
The problem with this is if you want to use the exception to then do some further processing the only way you can determine it was a duplicate key exception is to do some string matching on the message. This is because the code always appears to be 0 and nothing else about the exception identifies it as a duplicate key error. Its not particularly robust to rely on error messages, they can and do change over time. Given how much this new library has changed things means relying on this is rather fragile.
The old driver in the early versions throw a \MongoCursorException
which set the code on the exception to 11000. Later versions introduced a specific exception subclass called \MongoDuplicateKeyException
. Both of these were much more robust ways to detect and deal with specific types of error. See http://php.net/manual/en/book.mongo.php for more details on these exceptions.