Error handling

Error handling#

Errors raised by queues and listeners are passed to error handlers registered on the channel. Then the channel either re-raises them or, where it swallows them (e.g. a listener’s on_message, or a push during a broadcast), logs them.

Handlers are not persisted: register them on each channel, or once on a ChannelRepositoryBuilder, that registers them on every channel it creates or loads.

from eric_sse.handlers import ListenerErrorHandler

class AlertOnFailure(ListenerErrorHandler):
    def handle_on_message_error(self, connection_id, msg, exception):
        send_alert(f'{connection_id} failed on {msg.type}: {exception!r}')

channel.add_listener_error_handler(AlertOnFailure())

DataProcessingChannel handles errors the same way, running listeners in an executor: listener errors are handled in the channel’s process, and queue errors are re-raised after the messages already popped are processed.

Subclasses that notify listeners their own way get the same behaviour by popping with _pop_next() and passing listener errors to _on_listener_error().

See Dead Letter for a handler that implements a common pattern.

Stream errors#

message_stream() doesn’t raise: it yields errors to the client, formatted by adapt_error(), as messages are formatted by adapt().

SSEChannel sends them as SSE events of type error:

{
    "event": "error",
    "retry": 5,
    "data": {"error": "InternalStreamError", "message": "Internal error"}
}

Channels extending AbstractChannel directly must implement adapt_error; override it in prefab subclasses to change the format.

Timeouts are not errors: an idle stream waits wait_timeout_seconds for a message, then checks whether its listener is still running. Each time, the wait ends with a NoMessagesException, nothing is yielded, and the on_wait_timeout() hook is called, e.g. to collect metrics or to end idle streams.

See Error handlers for the classes.