NotUniqueError gracefully replacing ambiguous OperationError when appropriate

This commit is contained in:
Ross Lawley
2012-08-24 10:38:00 +01:00
parent eedf908770
commit 1c5e6a3425
4 changed files with 23 additions and 9 deletions

View File

@@ -1,18 +1,19 @@
import warnings
import pymongo
import re
from bson.dbref import DBRef
from mongoengine import signals, queryset
from base import (DocumentMetaclass, TopLevelDocumentMetaclass, BaseDocument,
BaseDict, BaseList)
from queryset import OperationError
from queryset import OperationError, NotUniqueError
from connection import get_db, DEFAULT_CONNECTION_NAME
__all__ = ['Document', 'EmbeddedDocument', 'DynamicDocument',
'DynamicEmbeddedDocument', 'OperationError',
'InvalidCollectionError']
'InvalidCollectionError', 'NotUniqueError']
class InvalidCollectionError(Exception):
@@ -250,8 +251,11 @@ class Document(BaseDocument):
except pymongo.errors.OperationFailure, err:
message = 'Could not save document (%s)'
if u'duplicate key' in unicode(err):
if re.match('^E1100[01] duplicate key', unicode(err)):
# E11000 - duplicate key error index
# E11001 - duplicate key on update
message = u'Tried to save duplicate unique keys (%s)'
raise NotUniqueError(message % unicode(err))
raise OperationError(message % unicode(err))
id_field = self._meta['id_field']
if id_field not in self._meta.get('shard_key', []):