Skip to content

Commit 4fd9777

Browse files
Show exception cause/context when printing an exception.
1 parent 5021832 commit 4fd9777

File tree

2 files changed

+20
-11
lines changed

2 files changed

+20
-11
lines changed

ptpython/printer.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -254,8 +254,7 @@ def _apply_soft_wrapping(
254254
columns_in_buffer += width
255255
current_line.append((style, c))
256256

257-
if len(current_line) > 0:
258-
yield current_line
257+
yield current_line
259258

260259
def _print_paginated_formatted_text(
261260
self, lines: Iterable[StyleAndTextTuples]
@@ -323,14 +322,20 @@ def show_pager() -> None:
323322
def _format_exception_output(
324323
self, e: BaseException, highlight: bool
325324
) -> Generator[OneStyleAndTextTuple, None, None]:
326-
# Instead of just calling ``traceback.format_exc``, we take the
327-
# traceback and skip the bottom calls of this framework.
328-
t, v, tb = sys.exc_info()
329-
330-
# Required for pdb.post_mortem() to work.
331-
sys.last_type, sys.last_value, sys.last_traceback = t, v, tb
332-
333-
tblist = list(traceback.extract_tb(tb))
325+
if e.__cause__:
326+
yield from self._format_exception_output(e.__cause__, highlight=highlight)
327+
yield (
328+
"",
329+
"\nThe above exception was the direct cause of the following exception:\n\n",
330+
)
331+
elif e.__context__:
332+
yield from self._format_exception_output(e.__context__, highlight=highlight)
333+
yield (
334+
"",
335+
"\nDuring handling of the above exception, another exception occurred:\n\n",
336+
)
337+
338+
tblist = list(traceback.extract_tb(e.__traceback__))
334339

335340
for line_nr, tb_tuple in enumerate(tblist):
336341
if tb_tuple[0] == "<stdin>":
@@ -340,7 +345,7 @@ def _format_exception_output(
340345
tb_list = traceback.format_list(tblist)
341346
if tb_list:
342347
tb_list.insert(0, "Traceback (most recent call last):\n")
343-
tb_list.extend(traceback.format_exception_only(t, v))
348+
tb_list.extend(traceback.format_exception_only(type(e), e))
344349

345350
tb_str = "".join(tb_list)
346351

ptpython/repl.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,10 @@ def _compile_with_flags(self, code: str, mode: str) -> Any:
378378
)
379379

380380
def _handle_exception(self, e: BaseException) -> None:
381+
# Required for pdb.post_mortem() to work.
382+
t, v, tb = sys.exc_info()
383+
sys.last_type, sys.last_value, sys.last_traceback = t, v, tb
384+
381385
self._get_output_printer().display_exception(
382386
e,
383387
highlight=self.enable_syntax_highlighting,

0 commit comments

Comments
 (0)