Skip to content

Commit df156b1

Browse files
committed
docs,tests: Add docs and test for uasyncio custom exc handler methods.
1 parent 15f41c2 commit df156b1

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

docs/library/uasyncio.rst

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,3 +266,22 @@ Event Loop
266266
.. method:: Loop.close()
267267

268268
Close the event loop.
269+
270+
.. method:: Loop.set_exception_handler(handler)
271+
272+
Set the exception handler to call when a Task raises an exception that is not
273+
caught. The *handler* should accept two arguments: ``(loop, context)``.
274+
275+
.. method:: Loop.get_exception_handler()
276+
277+
Get the current exception handler. Returns the handler, or ``None`` if no
278+
custom handler is set.
279+
280+
.. method:: Loop.default_exception_handler(context)
281+
282+
The default exception handler that is called.
283+
284+
.. method:: Loop.call_exception_handler(context)
285+
286+
Call the current exception handler. The argument *context* is passed through and
287+
is a dictionary containing keys: ``'message'``, ``'exception'``, ``'future'``.
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Test that tasks return their value correctly to the caller
2+
3+
try:
4+
import uasyncio as asyncio
5+
except ImportError:
6+
try:
7+
import asyncio
8+
except ImportError:
9+
print("SKIP")
10+
raise SystemExit
11+
12+
13+
def custom_handler(loop, context):
14+
print("custom_handler", repr(context["exception"]))
15+
16+
17+
async def task(i):
18+
# Raise with 2 args so exception prints the same in uPy and CPython
19+
raise ValueError(i, i + 1)
20+
21+
22+
async def main():
23+
loop = asyncio.get_event_loop()
24+
25+
# Check default exception handler, should be None
26+
print(loop.get_exception_handler())
27+
28+
# Set exception handler and test it was set
29+
loop.set_exception_handler(custom_handler)
30+
print(loop.get_exception_handler() == custom_handler)
31+
32+
# Create a task that raises and uses the custom exception handler
33+
asyncio.create_task(task(0))
34+
print("sleep")
35+
await asyncio.sleep(0)
36+
37+
# Create 2 tasks to test order of printing exception
38+
asyncio.create_task(task(1))
39+
asyncio.create_task(task(2))
40+
print("sleep")
41+
await asyncio.sleep(0)
42+
43+
print("done")
44+
45+
46+
asyncio.run(main())
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
None
2+
True
3+
sleep
4+
custom_handler ValueError(0, 1)
5+
sleep
6+
custom_handler ValueError(1, 2)
7+
custom_handler ValueError(2, 3)
8+
done

0 commit comments

Comments
 (0)