Skip to content

Commit

Permalink
Only show stack trace in debug mode (#1860)
Browse files Browse the repository at this point in the history
* Only show stack trace in dev mode

* Update custom exception handler to handle KeyboardInterrupts
  • Loading branch information
aaronatp authored Dec 8, 2023
1 parent d6f7d21 commit 8531acd
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions capa/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import datetime
import textwrap
import contextlib
from types import TracebackType
from typing import Any, Set, Dict, List, Callable, Optional
from pathlib import Path

Expand Down Expand Up @@ -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+")
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 8531acd

Please sign in to comment.