Skip to content

Commit e711408

Browse files
committed
PYTHON-1682 UTF-8 encode unicode error messages on Python 2
1 parent 341b2b5 commit e711408

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

pymongo/errors.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
"""Exceptions raised by PyMongo."""
1616

17+
import sys
18+
1719
from bson.errors import *
1820

1921
try:
@@ -26,6 +28,7 @@ class PyMongoError(Exception):
2628
"""Base class for all PyMongo exceptions."""
2729
def __init__(self, message='', error_labels=None):
2830
super(PyMongoError, self).__init__(message)
31+
self._message = message
2932
self._error_labels = set(error_labels or [])
3033

3134
def has_error_label(self, label):
@@ -43,6 +46,11 @@ def _remove_error_label(self, label):
4346
"""Remove the given label from this error."""
4447
self._error_labels.remove(label)
4548

49+
def __str__(self):
50+
if sys.version_info[0] == 2 and isinstance(self._message, unicode):
51+
return self._message.encode('utf-8', errors='replace')
52+
return str(self._message)
53+
4654

4755
class ProtocolError(PyMongoError):
4856
"""Raised for failures related to the wire protocol."""

test/test_collection.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1316,6 +1316,21 @@ def test_write_error_text_handling(self):
13161316
db.test.insert_many,
13171317
[{"text": text}])
13181318

1319+
def test_write_error_unicode(self):
1320+
coll = self.db.test
1321+
self.addCleanup(coll.drop)
1322+
1323+
coll.create_index('a', unique=True)
1324+
coll.insert_one({'a': u'unicode \U0001f40d'})
1325+
with self.assertRaisesRegex(
1326+
DuplicateKeyError,
1327+
'E11000 duplicate key error') as ctx:
1328+
coll.insert_one({'a': u'unicode \U0001f40d'})
1329+
1330+
# Once more for good measure.
1331+
self.assertIn('E11000 duplicate key error',
1332+
str(ctx.exception))
1333+
13191334
def test_wtimeout(self):
13201335
# Ensure setting wtimeout doesn't disable write concern altogether.
13211336
# See SERVER-12596.

0 commit comments

Comments
 (0)