Extract an exception type without exposing traceback paths
To extract an exception type without exposing traceback paths, derive a separate status field with type(error).__name__ and report that field rather than a formatted exception. Here an in-memory mapping is indexed with the rejected input "account=47". The resulting KeyError message contains that key. Formatting the active exception with traceback.format_exc() also contains the traceback heading and the fixture function name, which demonstrates that it carries diagnostic context beyond the category.
The correction is deliberately narrow: error_type is "KeyError", and the printed status contains only that value. The assertions establish that the full rendering contains both traceback context and the rejected input, while the type-only status has neither the input nor traceback text. They do not claim that examining a type name somehow removes data already sent elsewhere; the reporting code must choose the type-only field at its output boundary.
This classification can be useful for a compact status or counter, but it discards the exception message, arguments, traceback, and any chaining context. It also does not prove why the key was absent. Preserve richer diagnostics in an appropriate controlled destination if they are needed. Python's exception tutorial documents catching an exception with except ... as; type() and __name__ are long-standing Python 3 features, so this example has no newer minimum-version requirement.
Python documentation: Handling Exceptions · Python traceback documentation: format_exc
AI assistance disclosure: This synthetic example and explanation were prepared with AI assistance.
import traceback
def read_required(mapping, key):
return mapping[key]
settings = {"mode": "safe"}
rejected_input = "account=47"
try:
read_required(settings, rejected_input)
except LookupError as error:
full_diagnostic = traceback.format_exc()
error_message = str(error)
error_type = type(error).__name__
assert "Traceback (most recent call last):" in full_diagnostic
assert "read_required" in full_diagnostic
assert rejected_input in full_diagnostic
assert error_message == "'account=47'"
assert error_type == "KeyError"
assert rejected_input not in error_type
assert "Traceback" not in error_type
print(f"status type: {error_type}")
status type: KeyError