Batu Lab NotesPractical developer guides

Format a short exception-only diagnostic

By Batu · English technical notes

Also published in our primary archive.

To format a short exception-only diagnostic in Python, catch the error and call traceback.format_exception_only(type(error), error). This fixture rejects the concrete input "-2" and deliberately raises ValueError("invalid count"). In contrast, traceback.format_exc() creates a full rendering for the active exception: it includes a traceback heading and frame information. The corrected reporting boundary joins only the exception-only lines, producing ValueError: invalid count plus its newline.

The assertions make the contrast observable without putting a machine-specific frame display in stdout. One confirms that the full formatter contains the traceback heading; another confirms that its result includes the fixture’s function name. The exact assertion on short_diagnostic verifies the intended, stable rendering. This uses the module-level formatter documented by Python; it is available in supported Python 3 releases and needs no newer-version API.

Exception-only output is shorter, but it is not automatic sanitization. It still formats the exception message, so code should construct errors with an appropriate message or apply a separate reporting policy if that message could contain restricted data. Conversely, retaining the full traceback separately may be useful for debugging. This experiment only shows what these two formatters include for this synthetic caught exception.

Python traceback documentation: format_exception_only

AI assistance disclosure: This synthetic example and explanation were prepared with AI assistance.

import traceback


def parse_count(raw_value):
    count = int(raw_value)
    if count < 0:
        raise ValueError("invalid count")
    return count


try:
    parse_count("-2")
except ValueError as error:
    full_diagnostic = traceback.format_exc()
    short_diagnostic = "".join(
        traceback.format_exception_only(type(error), error)
    )

assert "Traceback (most recent call last):" in full_diagnostic
assert "parse_count" in full_diagnostic
assert short_diagnostic == "ValueError: invalid count\n"
print("format_exc has frames: True")
print(f"short diagnostic: {short_diagnostic}", end="")
format_exc has frames: True
short diagnostic: ValueError: invalid count