Skip to content

Commit bf0d936

Browse files
committed
Tweak cancellation output
1 parent 41877f0 commit bf0d936

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

hello/hello_cancellation.py

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
import asyncio
22
import time
3-
import traceback
43
from concurrent.futures import ThreadPoolExecutor
54
from datetime import timedelta
65
from typing import NoReturn
76

87
from temporalio import activity, workflow
98
from temporalio.client import Client, WorkflowFailureError
10-
from temporalio.exceptions import CancelledError
9+
from temporalio.exceptions import ActivityError, CancelledError
1110
from temporalio.worker import Worker
1211

1312

@@ -20,8 +19,10 @@ def never_complete_activity() -> NoReturn:
2019
print("Heartbeating activity")
2120
activity.heartbeat()
2221
time.sleep(1)
23-
except CancelledError:
24-
print("Activity cancelled")
22+
except CancelledError as err:
23+
print(
24+
f"Got expected exception in activity. Cause chain is {format_exception_cause_chain(err)}"
25+
)
2526
raise
2627

2728

@@ -43,6 +44,11 @@ async def run(self) -> None:
4344
# Always set a heartbeat timeout for long-running activities
4445
heartbeat_timeout=timedelta(seconds=2),
4546
)
47+
except ActivityError as err:
48+
print(
49+
f"Got expected exception in workflow. Cause chain is {format_exception_cause_chain(err)}"
50+
)
51+
raise
4652
finally:
4753
await workflow.execute_activity(
4854
cleanup_activity, start_to_close_timeout=timedelta(seconds=5)
@@ -61,7 +67,6 @@ async def main():
6167
activities=[never_complete_activity, cleanup_activity],
6268
activity_executor=ThreadPoolExecutor(5),
6369
):
64-
6570
# While the worker is running, use the client to start the workflow.
6671
# Note, in many production setups, the client would be in a completely
6772
# separate process from the worker.
@@ -80,8 +85,17 @@ async def main():
8085
try:
8186
await handle.result()
8287
raise RuntimeError("Should not succeed")
83-
except WorkflowFailureError:
84-
print("Got expected exception: ", traceback.format_exc())
88+
except WorkflowFailureError as err:
89+
print(
90+
f"Got expected exception in client. Cause chain is {format_exception_cause_chain(err)}"
91+
)
92+
93+
94+
def format_exception_cause_chain(err: BaseException) -> str:
95+
causes = [err]
96+
while cause := causes[-1].__cause__:
97+
causes.append(cause)
98+
return " -> ".join([f"{e.__class__.__name__}" for e in causes])
8599

86100

87101
if __name__ == "__main__":

0 commit comments

Comments
 (0)