Reputation: 8961
from pymongo.errors import DuplicateKeyError
def insert_duplicate_token(self):
try:
fields = ..
token = Token.create_a_new_document(fields)
token.save()
token = Token.create_a_new_document(fields)
token.save()
self.logger.info('success')
except DuplicateKeyError:
self.logger.exception('Duplicate caught')
except Exception, err:
self.logger.exception('failed...')
return False
The error raised is u'Tried to save duplicate unique keys (E11000 duplicate key error collection: oauth_test.tokens index: idx_access_token dup key: { : "gRULKp6sqPWRYDrJNrvaifMhlaC8qvzfZOpqTZLTPxHnQ691vT" })'
but is caught in Exception
, and not in DuplicateKeyError
tried
import pymongo
pymongo.errors - does not exists
here is the stacktrace
Traceback (most recent call last):
File "move_invalid_tokens_worker.py", line 91, in insert_duplicate_token
token.save()
File "/Users/ohadperry/.virtualenvs/oauth/lib/python2.7/site-packages/mongoengine/document.py", line 386, in save
raise NotUniqueError(message % unicode(err))
NotUniqueError: Tried to save duplicate unique keys (E11000 duplicate key error collection: oauth_test.tokens index: access_token_1 dup key: { : "MIeJey0f3rWkedMZacDIjDMB3a04ilrbdieKaZ2BWt0lI0sATP" })
weird..
Upvotes: 1
Views: 1713
Reputation: 8961
I answered myself with the stackstrace, thanks @Arount
from pymongo.errors import DuplicateKeyError
from mongoengine import NotUniqueError
def insert_duplicate_token(self):
try:
fields = ..
token = Token.create_a_new_document(fields)
token.save()
token = Token.create_a_new_document(fields)
token.save()
self.logger.info('success')
except (NotUniqueError, DuplicateKeyError), error:
self.logger.exception('Duplicate caught')
except Exception, error:
self.logger.exception('failed...')
return False
Upvotes: 3