from types import TracebackType
from typing import Optional, Tuple, Type
from lineapy.exceptions.flag import REWRITE_EXCEPTIONS
from lineapy.exceptions.user_exception import (
ExceptHookArgs = Tuple[Type[Exception], Exception, Optional[TracebackType]]
args: ExceptHookArgs, *changes: TracebackChange
) -> ExceptHookArgs:
Used by both CLI and Jupyter to pull out the cause from a user exception
and also apply the changes to the frames if it's a `UserException`, which
is a custom exception that WE created.
`changes` is for Jupyter notebook support. They were discovered through trial and error with different type
of executions, as seen in `executor.py`.
If the error is from lineapy, we keep the original frames.
# the 2nd arg is the Exception (per the docs, and described in
exc_value = args
if isinstance(exc_value, UserException):
# the user's exception
cause = exc_value.__cause__
return type(cause), cause, cause.__traceback__
Sets an exception hook, so that if an exception is raised, if it's a user
exception, then the traceback will only be the inner cause, not the outer frames.
return sys.__excepthook__(*transform_except_hook_args(args)) # type: ignore
To support CLI error reporting (or the repl, which we do not currently have).
sys.excepthook = custom_excepthook