Skip to content
Merged
Show file tree
Hide file tree
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
10 changes: 8 additions & 2 deletions can/listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,15 @@ def __call__(self, msg: Message) -> None:
self.on_message_received(msg)

def on_error(self, exc: Exception) -> None:
"""This method is called to handle any exception in the receive thread.
"""Handle an exception related to this listener.

:param exc: The exception causing the thread to stop
This method is called when receiving messages for this listener fails or
when this listener fails to process a message. Return normally if the
exception is handled. The default implementation raises
:class:`NotImplementedError` to signal that this listener does not handle
exceptions. See :class:`~can.Notifier` for how it calls this method.

:param exc: The exception to handle
"""
raise NotImplementedError()

Expand Down
102 changes: 74 additions & 28 deletions can/notifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,22 @@ def __init__(
Remember to call :meth:`~can.Notifier.stop` after all messages are received as
many listeners carry out flush operations to persist data.

If receiving from a bus fails, the notifier calls
:meth:`~can.Listener.on_error` of every listener that implements it. After
such a bus error, reception from that bus continues only if the notifier
runs without an event loop and at least one listener handled the error.

If a listener, or a coroutine it returned, raises an exception, the notifier
calls :meth:`~can.Listener.on_error` of that listener only and keeps
delivering messages to the other listeners. If the listener does not handle
the exception, the notifier logs it and, while running, removes the
listener and calls its ``stop()`` method.

An exception counts as handled if ``on_error()`` returns normally. If
``on_error()`` raises :class:`NotImplementedError` or any other exception,
the original exception counts as not handled; any other exception is also
logged.


:param bus:
A :ref:`bus` or a list of buses to consume messages from.
Expand All @@ -138,7 +154,8 @@ def __init__(
self.timeout = timeout
self._loop = loop

#: Exception raised in thread
#: The most recent exception raised by a bus or a listener,
#: whether or not it was handled.
self.exception: Exception | None = None

self._stopped = False
Expand Down Expand Up @@ -213,7 +230,7 @@ def stop(self, timeout: float = 5.0) -> None:
elif self._loop:
# reader is a file descriptor
self._loop.remove_reader(reader)
for listener in self.listeners:
for listener in tuple(self.listeners):
if hasattr(listener, "stop"):
listener.stop()

Expand All @@ -226,7 +243,7 @@ def _rx_thread(self, bus: BusABC) -> None:
if self._loop:
handle_message: Callable[[Message], Any] = functools.partial(
self._loop.call_soon_threadsafe,
self._on_message_received_with_error_handling, # type: ignore[arg-type]
self._on_message_received, # type: ignore[arg-type]
)
else:
handle_message = self._on_message_received
Expand Down Expand Up @@ -260,29 +277,24 @@ def _on_message_available(self, bus: BusABC) -> None:
logger.debug("suppressed exception: %s", exc)
else:
if msg:
self._on_message_received_with_error_handling(msg)

def _on_message_received_with_error_handling(self, msg: Message) -> None:
try:
self._on_message_received(msg)
except Exception as exc: # pylint: disable=broad-except
self.exception = exc
if not self._on_error(exc):
raise
logger.debug("suppressed exception: %s", exc)
self._on_message_received(msg)

def _on_message_received(self, msg: Message) -> None:
for callback in self.listeners:
for callback in tuple(self.listeners):
if self._stopped:
return
res = callback(msg)
try:
res = callback(msg)
except Exception as exc: # noqa: BLE001 # pylint: disable=broad-except
self._on_listener_error(callback, exc)
continue
if res and self._loop and asyncio.iscoroutine(res):
# Schedule coroutine and keep a reference to the task
task = self._loop.create_task(res)
self._tasks.add(task)
task.add_done_callback(self._on_task_done)
task.add_done_callback(functools.partial(self._on_task_done, callback))

def _on_task_done(self, task: asyncio.Task) -> None:
def _on_task_done(self, callback: MessageRecipient, task: asyncio.Task) -> None:
self._tasks.discard(task)
if task.cancelled():
return
Expand All @@ -292,10 +304,29 @@ def _on_task_done(self, task: asyncio.Task) -> None:
if not isinstance(exc, Exception):
return

self._on_listener_error(callback, exc)

def _on_listener_error(self, callback: MessageRecipient, exc: Exception) -> None:
"""Pass an exception raised by a listener to that listener only.

Log the exception if the listener does not handle it, and stop and
remove the listener while the notifier runs.
"""
self.exception = exc
if not self._on_error(exc):
raise exc
logger.debug("suppressed exception: %s", exc)
if self._call_error_handler(callback, exc):
logger.debug("suppressed exception: %s", exc)
elif not self._stopped and callback in self.listeners:
self.remove_listener(callback)
logger.error(
"removed listener %r after unhandled exception", callback, exc_info=exc
)
if hasattr(callback, "stop"):
try:
callback.stop()
except Exception: # pylint: disable=broad-except
logger.exception("stopping listener %r failed", callback)
else:
logger.error("unhandled exception in listener %r", callback, exc_info=exc)

def _on_error(self, exc: Exception) -> bool:
"""Calls ``on_error()`` for all listeners if they implement it.
Expand All @@ -304,17 +335,32 @@ def _on_error(self, exc: Exception) -> bool:
"""
was_handled = False

for listener in self.listeners:
if hasattr(listener, "on_error"):
try:
listener.on_error(exc)
except NotImplementedError:
pass
else:
was_handled = True
for listener in tuple(self.listeners):
if self._call_error_handler(listener, exc):
was_handled = True

return was_handled

@staticmethod
def _call_error_handler(listener: MessageRecipient, exc: Exception) -> bool:
"""Call ``on_error()`` of *listener* if it implements it.

:returns: ``True`` if the error handler returned normally.
"""
on_error: Callable[[Exception], None] | None = getattr(
listener, "on_error", None
)
if on_error is None:
return False
try:
on_error(exc)
except NotImplementedError:
return False
except Exception: # pylint: disable=broad-except
logger.exception("error handler of listener %r failed", listener)
return False
return True

def add_listener(self, listener: MessageRecipient) -> None:
"""Add new Listener to the notification set.

Expand Down
1 change: 1 addition & 0 deletions doc/changelog.d/2183.changed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
``can.Notifier`` passes an exception raised by a listener or its coroutine only to that listener's ``on_error()``, no longer to the ``on_error()`` of all listeners, and still delivers the message to all other listeners; if the failing listener does not handle the exception, the notifier logs it, removes the listener and calls its ``stop()`` method instead of stopping the receive thread or reporting to the event loop's exception handler, so a listener that relied on another listener's ``on_error()`` to keep receiving messages must now implement ``on_error()`` itself. An exception raised by ``on_error()``, also for receive errors of a bus, is now logged and counts as not handled by that listener.
Loading
Loading