Skip to content

Commit 296372e

Browse files
committed
PYTHON-5449 - Do not attach invalid document in exception message
1 parent eca38b7 commit 296372e

File tree

4 files changed

+31
-16
lines changed

4 files changed

+31
-16
lines changed

bson/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1009,7 +1009,7 @@ def _dict_to_bson(
10091009
try:
10101010
elements.append(_element_to_bson(key, value, check_keys, opts))
10111011
except InvalidDocument as err:
1012-
raise InvalidDocument(f"Invalid document {doc} | {err}") from err
1012+
raise InvalidDocument(f"Invalid document: {err}", doc) from err
10131013
except AttributeError:
10141014
raise TypeError(f"encoder expected a mapping type but got: {doc!r}") from None
10151015

bson/_cbsonmodule.c

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1645,7 +1645,7 @@ static int write_raw_doc(buffer_t buffer, PyObject* raw, PyObject* _raw_str) {
16451645
}
16461646

16471647

1648-
/* Update Invalid Document error message to include doc.
1648+
/* Update Invalid Document error to include doc as a property.
16491649
*/
16501650
void handle_invalid_doc_error(PyObject* dict) {
16511651
PyObject *etype = NULL, *evalue = NULL, *etrace = NULL;
@@ -1659,20 +1659,13 @@ void handle_invalid_doc_error(PyObject* dict) {
16591659
if (evalue && PyErr_GivenExceptionMatches(etype, InvalidDocument)) {
16601660
PyObject *msg = PyObject_Str(evalue);
16611661
if (msg) {
1662-
// Prepend doc to the existing message
1663-
PyObject *dict_str = PyObject_Str(dict);
1664-
if (dict_str == NULL) {
1665-
goto cleanup;
1666-
}
1667-
const char * dict_str_utf8 = PyUnicode_AsUTF8(dict_str);
1668-
if (dict_str_utf8 == NULL) {
1669-
goto cleanup;
1670-
}
1662+
// Add doc to the error class as a property.
1663+
PyObject_SetAttrString(InvalidDocument, "document", dict);
16711664
const char * msg_utf8 = PyUnicode_AsUTF8(msg);
16721665
if (msg_utf8 == NULL) {
16731666
goto cleanup;
16741667
}
1675-
PyObject *new_msg = PyUnicode_FromFormat("Invalid document %s | %s", dict_str_utf8, msg_utf8);
1668+
PyObject *new_msg = PyUnicode_FromFormat("Invalid document: %s", msg_utf8);
16761669
Py_DECREF(evalue);
16771670
Py_DECREF(etype);
16781671
etype = InvalidDocument;

bson/errors.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
"""Exceptions raised by the BSON package."""
1616
from __future__ import annotations
1717

18+
from typing import Any, Optional
19+
1820

1921
class BSONError(Exception):
2022
"""Base class for all BSON exceptions."""
@@ -31,6 +33,19 @@ class InvalidStringData(BSONError):
3133
class InvalidDocument(BSONError):
3234
"""Raised when trying to create a BSON object from an invalid document."""
3335

36+
def __init__(self, message: str, document: Optional[Any] = None) -> None:
37+
super().__init__(message)
38+
self._document = document
39+
40+
@property
41+
def document(self) -> Any:
42+
"""The invalid document that caused the error."""
43+
return self._document
44+
45+
@document.setter
46+
def document(self, value: Any) -> None:
47+
self._document = value
48+
3449

3550
class InvalidId(BSONError):
3651
"""Raised when trying to create an ObjectId from invalid data."""

test/test_bson.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1163,7 +1163,7 @@ def __repr__(self):
11631163
):
11641164
encode({"t": Wrapper(1)})
11651165

1166-
def test_doc_in_invalid_document_error_message(self):
1166+
def test_doc_in_invalid_document_error_as_property(self):
11671167
class Wrapper:
11681168
def __init__(self, val):
11691169
self.val = val
@@ -1173,10 +1173,11 @@ def __repr__(self):
11731173

11741174
self.assertEqual("1", repr(Wrapper(1)))
11751175
doc = {"t": Wrapper(1)}
1176-
with self.assertRaisesRegex(InvalidDocument, f"Invalid document {doc}"):
1176+
with self.assertRaisesRegex(InvalidDocument, "Invalid document:") as cm:
11771177
encode(doc)
1178+
self.assertEqual(cm.exception.document, doc)
11781179

1179-
def test_doc_in_invalid_document_error_message_mapping(self):
1180+
def test_doc_in_invalid_document_error_as_property_mapping(self):
11801181
class MyMapping(abc.Mapping):
11811182
def keys(self):
11821183
return ["t"]
@@ -1192,6 +1193,11 @@ def __len__(self):
11921193
def __iter__(self):
11931194
return iter(["t"])
11941195

1196+
def __eq__(self, other):
1197+
if isinstance(other, MyMapping):
1198+
return True
1199+
return False
1200+
11951201
class Wrapper:
11961202
def __init__(self, val):
11971203
self.val = val
@@ -1201,8 +1207,9 @@ def __repr__(self):
12011207

12021208
self.assertEqual("1", repr(Wrapper(1)))
12031209
doc = MyMapping()
1204-
with self.assertRaisesRegex(InvalidDocument, f"Invalid document {doc}"):
1210+
with self.assertRaisesRegex(InvalidDocument, "Invalid document:") as cm:
12051211
encode(doc)
1212+
self.assertEqual(cm.exception.document, doc)
12061213

12071214

12081215
class TestCodecOptions(unittest.TestCase):

0 commit comments

Comments
 (0)