Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
PYTHON-1682 UTF-8 encode unicode error messages on Python 2
- Loading branch information
1 parent
341b2b5
commit e711408
Showing
2 changed files
with
23 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -14,6 +14,8 @@ | |
|
||
"""Exceptions raised by PyMongo.""" | ||
|
||
import sys | ||
|
||
from bson.errors import * | ||
|
||
try: | ||
|
@@ -26,6 +28,7 @@ class PyMongoError(Exception): | |
"""Base class for all PyMongo exceptions.""" | ||
def __init__(self, message='', error_labels=None): | ||
super(PyMongoError, self).__init__(message) | ||
self._message = message | ||
self._error_labels = set(error_labels or []) | ||
|
||
def has_error_label(self, label): | ||
|
@@ -43,6 +46,11 @@ def _remove_error_label(self, label): | |
"""Remove the given label from this error.""" | ||
self._error_labels.remove(label) | ||
|
||
def __str__(self): | ||
if sys.version_info[0] == 2 and isinstance(self._message, unicode): | ||
This comment has been minimized.
Sorry, something went wrong.
This comment has been minimized.
Sorry, something went wrong.
Kami
|
||
return self._message.encode('utf-8', errors='replace') | ||
return str(self._message) | ||
|
||
|
||
class ProtocolError(PyMongoError): | ||
"""Raised for failures related to the wire protocol.""" | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Just a heads up - this breaks mongoengine when an error message contains non-ascii data and default encoding used by Python is not
utf8
.See MongoEngine/mongoengine#1428 (comment) for details.
I'm looking into a fix on the mongoengine level although this could affect other code which pymongo which doesn't use utf8 encoding by default (it's fairly common for Python encoding to still default to
ascii
).