Skip to content

Commit

Permalink
feat: Add __notes__ support (#3620)
Browse files Browse the repository at this point in the history
* Add support for add_note()

* Ignore non-str notes

* minor tweaks

---------

Co-authored-by: Arjen Nienhuis <[email protected]>
  • Loading branch information
szokeasaurusrex and arjenzorgdoc authored Oct 8, 2024
1 parent a31c54f commit 2d2e548
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
14 changes: 12 additions & 2 deletions sentry_sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -713,11 +713,21 @@ def get_errno(exc_value):

def get_error_message(exc_value):
# type: (Optional[BaseException]) -> str
return (
message = (
getattr(exc_value, "message", "")
or getattr(exc_value, "detail", "")
or safe_str(exc_value)
)
) # type: str

# __notes__ should be a list of strings when notes are added
# via add_note, but can be anything else if __notes__ is set
# directly. We only support strings in __notes__, since that
# is the correct use.
notes = getattr(exc_value, "__notes__", None) # type: object
if isinstance(notes, list) and len(notes) > 0:
message += "\n" + "\n".join(note for note in notes if isinstance(note, str))

return message


def single_exception_from_error_tuple(
Expand Down
43 changes: 43 additions & 0 deletions tests/test_basics.py
Original file line number Diff line number Diff line change
Expand Up @@ -999,3 +999,46 @@ def test_hub_current_deprecation_warning():
def test_hub_main_deprecation_warnings():
with pytest.warns(sentry_sdk.hub.SentryHubDeprecationWarning):
Hub.main


@pytest.mark.skipif(sys.version_info < (3, 11), reason="add_note() not supported")
def test_notes(sentry_init, capture_events):
sentry_init()
events = capture_events()
try:
e = ValueError("aha!")
e.add_note("Test 123")
e.add_note("another note")
raise e
except Exception:
capture_exception()

(event,) = events

assert event["exception"]["values"][0]["value"] == "aha!\nTest 123\nanother note"


@pytest.mark.skipif(sys.version_info < (3, 11), reason="add_note() not supported")
def test_notes_safe_str(sentry_init, capture_events):
class Note2:
def __repr__(self):
raise TypeError

def __str__(self):
raise TypeError

sentry_init()
events = capture_events()
try:
e = ValueError("aha!")
e.add_note("note 1")
e.__notes__.append(Note2()) # type: ignore
e.add_note("note 3")
e.__notes__.append(2) # type: ignore
raise e
except Exception:
capture_exception()

(event,) = events

assert event["exception"]["values"][0]["value"] == "aha!\nnote 1\nnote 3"

0 comments on commit 2d2e548

Please sign in to comment.