KubeMQ
Client SDKsPythonHow-to guidesError Handling

Connection Error

Handle KubeMQ connection failures gracefully with the Python SDK, catching errors and reporting them cleanly.

Overview

A network partition, a server that hasn't started yet, or a typo in the address are all normal facts of life in distributed systems — and a client that blocks indefinitely or crashes with an unhandled exception turns a routine outage into a cascading failure. Fail-fast connection checking lets you detect an unreachable KubeMQ server the moment you call connect(), so your service can log the failure, alert, or fall back instead of hanging.

connect() attempts to establish the gRPC channel and raises KubeMQConnectionError — a subclass of the base KubeMQError — the instant it cannot reach the server, rather than deferring the failure to some later operation. Catching that specific subclass lets you log or retry with meaningful context, while a broader except Exception still catches anything unexpected. Gotchas: catch KubeMQConnectionError before the generic Exception handler, or the more specific diagnostics never run; a successful connect() doesn't guarantee the connection stays healthy, so you still need reconnection handling for failures that happen mid-session; swallowing the broad except Exception silently hides bugs unrelated to connectivity, so always log the exception type and message.

Prerequisites

  • KubeMQ server running on localhost:50000
  • Python SDK installed (pip install kubemq)

Code

connection_error.py
"""Example: Connection error — handle connection failures gracefully."""

from __future__ import annotations

import asyncio

from kubemq import KubeMQConnectionError
from kubemq import AsyncQueuesClient


async def main() -> None:
    try:
        # Attempt to connect to a non-existent server
        client = AsyncQueuesClient(
            address="localhost:59999",
            client_id="python-error-handling-connection-error-client",
        )
        await client.connect()
        server_info = await client.ping()
        print(f"Connected: {server_info}")
    except KubeMQConnectionError as e:
        print(f"Connection error (expected): {e}")
        print("  Tip: Verify the KubeMQ server is running at the specified address")
    except Exception as e:
        print(f"Unexpected error: {type(e).__name__}: {e}")


if __name__ == "__main__":
    asyncio.run(main())

How It Works

The client is intentionally pointed at localhost:59999 — an address with no server. connect() attempts to establish the gRPC channel; when it cannot reach the server it raises KubeMQConnectionError. Catching that specific subclass lets you log or retry with meaningful context, while the outer except Exception catches any unexpected failure. This pattern documents the exact exception hierarchy: KubeMQConnectionError is a subclass of KubeMQError.

Was this page helpful?

On this page