# Connection Error (/sdks/ruby/how-to/error-handling/connection-error)



## Overview [#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 `ping`, so your service can log the failure, alert, or fall back instead of hanging.

When the broker is unreachable, `ping` raises `KubeMQ::ConnectionError`, a subclass of the base `KubeMQ::Error`. Rescuing the base class handles connection failures broadly, while rescuing specific subclasses lets you target recovery logic to the failure at hand; every error also exposes `code`, `retryable?`, `suggestion`, and `cause` for diagnostic context. &#x2A;*Gotchas:** rescue the specific `KubeMQ::ConnectionError` before the broader `StandardError`, or you lose the targeted diagnostics; `retryable?` reflects the failure category, not your retry budget — retrying an unreachable server in a tight loop just multiplies the outage; `client&.close` in `ensure` only helps if `client` was actually assigned, so a failure during construction itself still needs to be handled explicitly.

## Prerequisites [#prerequisites]

* Ruby SDK installed (`gem install kubemq`)

## Code [#code]

```ruby title="main.rb"
require 'kubemq'

begin
  puts 'Attempting connection to bad address...'
  client = KubeMQ::PubSubClient.new(address: 'localhost:59999', client_id: 'error-example')
  client.ping
  puts 'Connected (unexpected)'
rescue KubeMQ::Error => e
  puts "Connection error (expected): #{e.message}"
rescue StandardError => e
  puts "Connection error (expected): #{e.message}"
ensure
  client&.close
  puts 'Done'
end
```

## How It Works [#how-it-works]

* When the broker is unreachable, `ping` raises `KubeMQ::ConnectionError`.
* Rescue `KubeMQ::Error` for broad error handling, or specific subclasses for targeted recovery.
* Each error provides `code`, `retryable?`, `suggestion`, and `cause` for diagnostic context.
* Review timeouts, channel names, and client IDs before running against shared environments.

## Related [#related]

* [Ruby SDK Reference — Types & Errors](/sdks/ruby/reference/types-and-errors)
* [Reconnection](/sdks/ruby/how-to/error-handling/reconnection)
* [Graceful Shutdown](/sdks/ruby/how-to/error-handling/graceful-shutdown)
