Only show stack trace in debug mode (#1860)

* Only show stack trace in dev mode

* Update custom exception handler to handle KeyboardInterrupts
This commit is contained in:
aaronatp
2023-12-08 15:07:16 -06:00
committed by GitHub
parent d6f7d2180f
commit 8531acd7c5

View File

@@ -18,6 +18,7 @@ import argparse
import datetime
import textwrap
import contextlib
from types import TracebackType
from typing import Any, Set, Dict, List, Callable, Optional
from pathlib import Path
@@ -977,6 +978,27 @@ def handle_common_args(args):
args.signatures = sigs_path
def simple_message_exception_handler(exctype, value: BaseException, traceback: TracebackType):
"""
prints friendly message on unexpected exceptions to regular users (debug mode shows regular stack trace)
args:
# TODO(aaronatp): Once capa drops support for Python 3.8, move the exctype type annotation to
# the function parameters and remove the "# type: ignore[assignment]" from the relevant place
# in the main function, see (https://github.com/mandiant/capa/issues/1896)
exctype (type[BaseException]): exception class
"""
if exctype is KeyboardInterrupt:
print("KeyboardInterrupt detected, program terminated")
else:
print(
f"Unexpected exception raised: {exctype}. Please run capa in debug mode (-d/--debug) "
+ "to see the stack trace. Please also report your issue on the capa GitHub page so we "
+ "can improve the code! (https://github.com/mandiant/capa/issues)"
)
def main(argv: Optional[List[str]] = None):
if sys.version_info < (3, 8):
raise UnsupportedRuntimeError("This version of capa can only be used with Python 3.8+")
@@ -1019,6 +1041,8 @@ def main(argv: Optional[List[str]] = None):
install_common_args(parser, {"sample", "format", "backend", "os", "signatures", "rules", "tag"})
parser.add_argument("-j", "--json", action="store_true", help="emit JSON instead of text")
args = parser.parse_args(args=argv)
if not args.debug:
sys.excepthook = simple_message_exception_handler # type: ignore[assignment]
ret = handle_common_args(args)
if ret is not None and ret != 0:
return ret