Skip to content

Commit

Permalink
Merge pull request #148 from OFFIS-DAI/scheduling-error-handling-canc…
Browse files Browse the repository at this point in the history
…elling

Added handling for cancelled tasks for the callback raise exception
  • Loading branch information
emiliefro authored Jan 3, 2025
2 parents ba9c4c1 + 41986f6 commit 4c05dac
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
15 changes: 9 additions & 6 deletions mango/util/scheduling.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,17 @@

def _raise_exceptions(fut: asyncio.Future):
"""
Inline function used as a callback to raise exceptions
Inline function used as a callback to raise exceptions.
:param fut: The Future object of the task
"""
if fut.exception() is not None:
try:
raise fut.exception()
except Exception:
logger.exception("got exception in scheduled event")
try:
if fut.exception() is not None:
try:
raise fut.exception()
except BaseException:
logger.exception("got exception in scheduled event")
except asyncio.CancelledError:
pass # if this happens the task has been cancelled by mango


@dataclass
Expand Down
25 changes: 25 additions & 0 deletions tests/unit_tests/util/scheduling_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import datetime
import logging
import time

import pytest
Expand Down Expand Up @@ -501,3 +502,27 @@ def on_stop(fut):
# THEN
assert len(l) == 2
assert l[1] == 2


class MyException(Exception):
pass


@pytest.mark.asyncio
async def test_exception(caplog):
# GIVEN
scheduler = Scheduler()
l = []

async def increase_counter():
raise MyException()

# WHEN
t = scheduler.schedule_task(PeriodicScheduledTask(increase_counter, 0.2))

# THEN
with caplog.at_level(logging.ERROR):
with pytest.raises(MyException):
await asyncio.wait_for(t, timeout=0.3)

assert "got exception in scheduled event" in caplog.text

0 comments on commit 4c05dac

Please sign in to comment.