Hacktoberfest 2026: los issues que los mantenedores marcaron para octubre, abiertos y aptos para principiantes. Explorar issues de Hacktoberfest

Async notifier does not handle errors

Abierto
#1,865 0 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
38/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Estancado
Stack tecnológico
python
Área
backend

Línea de trabajo

Comienza en notifier.py con Notifier._on_message_available y AsyncBufferedReader. Traza cómo los errores de bus.recv() llegan a _on_error() y cómo la coroutine que está esperando consume la cola de mensajes. Se considera terminado cuando los errores de recepción asíncronos llegan a los listeners y las coroutines que esperan pueden gestionarlos sin quedar bloqueadas, preservando el orden de los mensajes.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug

Greetings! I'm using python-can to talk to my inverter's battery.

Describe the bug

In class Notifier:

    def _on_message_available(self, bus: BusABC) -> None:
        if msg := bus.recv(0):
            self._on_message_received(msg)

When an exception occurs, for example the CAN interface going down or being unplugged, bus.recv() raises but the exception is not handled. The threaded version does call _on_error(), so I guess the async version should too. I fixed it by inheriting the class, but these 3 lines of code would be better in notifier.py.

class Notifier_e (can.Notifier):
    def _on_message_available(self, bus):
        try:
            super()._on_message_available(bus)
        except Exception as exc:
            if not self._on_error(exc):
                # If it was not handled, raise the exception here
                raise

Then _on_error() passes the exception to the listeners, for example AsyncBufferedReader, but it doesn't handle exceptions either: instead the coroutine waiting for messages simply stays stuck forever. So I extended it in the same way:

class AsyncBufferedReader_e( can.AsyncBufferedReader ):
    def on_error( self, exc ):
        self.buffer.put_nowait( exc )

    async def __anext__(self):
        m = await self.buffer.get()
        if isinstance( m, BaseException ):
            raise m
        return m

It puts the exception into the queue with messages, so when the coroutine waiting on these messages gets to the exception, it is raised, and the coroutine can process it. This preserves order between messages and exceptions, so messages received and pushed into the queue before the exception occurs will be processed.

I use it to cleanly disconnect the CAN interface, then connect again when it is plugged back into the USB port.

I'm not sure about Exception vs BaseException. I guess it would be useful to pass KeyboardInterrupt to the waiting coroutine, so it would be terminated in the same way as a Ctrl-C occurring during a blocking recv().

Have a nice day!

Lenguaje dominante
Python
Estrellas
1.6k
Forks
697
Métricas de merge de PR
Sin PR fusionados en 30 d

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de hardbyte/python-can

Todos los issues de hardbyte/python-can

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.