Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve catch_unhandled_exceptions #6358

Merged
merged 1 commit into from
May 18, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions distributed/tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3644,28 +3644,37 @@ async def hard_stop(s):
await c._close(fast=True)


class UnhandledException(Exception):
class UnhandledExceptions(Exception):
pass


@contextmanager
def catch_unhandled_exceptions() -> Generator[None, None, None]:
loop = asyncio.get_running_loop()
ctx: dict[str, Any] | None = None
ctxs: list[dict[str, Any]] = []

old_handler = loop.get_exception_handler()

@loop.set_exception_handler
def _(loop: object, context: dict[str, Any]) -> None:
nonlocal ctx
ctx = context
ctxs.append(context)

try:
yield
finally:
loop.set_exception_handler(old_handler)
if ctx:
raise UnhandledException(ctx["message"]) from ctx.get("exception")
if ctxs:
msgs = []
for i, ctx in enumerate(ctxs, 1):
msgs.append(ctx["message"])
print(
f"------ Unhandled exception {i}/{len(ctxs)}: {ctx['message']!r} ------"
)
print(ctx)
if exc := ctx.get("exception"):
traceback.print_exception(type(exc), exc, exc.__traceback__)

raise UnhandledExceptions(", ".join(msgs))


@gen_cluster(client=True, nthreads=[], client_kwargs={"timeout": 0.5})
Expand Down