# Connection Error (/sdks/nodejs/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 throws an opaque error turns a routine outage into a cascading failure. **Fail-fast connection checking** lets you detect an unreachable KubeMQ server the moment you call `KubeMQClient.create()`, bounded by `connectionTimeoutSeconds`, so your service can log the failure, alert, or fall back instead of hanging.

`create()` throws a typed `ConnectionError` (or `KubeMQTimeoutError` once the timeout elapses) instead of hanging forever, and a separate `ConfigurationError` when the options are invalid — before any network I/O happens. All SDK errors extend the base `KubeMQError`, so `err.code` gives you the machine-readable error code and `err.isRetryable` tells you whether attempting again is worthwhile. &#x2A;*Gotchas:** check the specific subclass (`ConnectionError` vs `ConfigurationError` vs `AuthenticationError`) before the generic `KubeMQError` branch, or you lose the actionable `err.suggestion`; `isRetryable` reflects the failure category, not your retry budget — retrying an unreachable server in a tight loop just multiplies the outage; a successful `create()` doesn't guarantee the connection stays up, so mid-session drops still need reconnection handling.

## Prerequisites [#prerequisites]

* KubeMQ server running on `localhost:50000`
* Node.js SDK installed (`npm install kubemq-js`)

## Code [#code]

```typescript title="connection-error.ts"
/**
 * Example: Connection Error Handling
 *
 * Demonstrates handling connection errors when the KubeMQ server is
 * unreachable, misconfigured, or requires authentication. Shows how
 * to catch specific error types and provide actionable diagnostics.
 *
 * Prerequisites:
 *   - This example intentionally connects to an invalid address.
 *
 * Run: npx tsx examples/error-handling/connection-error.ts
 */
import {
  KubeMQClient,
  ConnectionError,
  AuthenticationError,
  KubeMQTimeoutError,
  ConfigurationError,
  KubeMQError,
} from 'kubemq-js';

async function main(): Promise<void> {
  // --- Scenario 1: Unreachable server ---
  console.log('=== Scenario 1: Unreachable Server ===');
  try {
    await KubeMQClient.create({
      address: 'localhost:59999',
      clientId: 'js-error-handling-connection-error-client',
      connectionTimeoutSeconds: 3,
    });
  } catch (err) {
    if (err instanceof ConnectionError) {
      console.log('ConnectionError caught:', err.message);
      console.log('  Error code:', err.code);
      console.log('  Is retryable:', err.isRetryable);
      if (err.suggestion) {
        console.log('  Suggestion:', err.suggestion);
      }
    } else if (err instanceof KubeMQTimeoutError) {
      console.log('TimeoutError: Server did not respond within 3 seconds');
    } else {
      console.log('Unexpected error:', (err as Error).message);
    }
  }

  // --- Scenario 2: Invalid configuration ---
  console.log('\n=== Scenario 2: Invalid Configuration ===');
  try {
    await KubeMQClient.create({
      address: '',
      clientId: 'js-error-handling-connection-error-invalid-client',
    });
  } catch (err) {
    if (err instanceof ConfigurationError) {
      console.log('ConfigurationError caught:', err.message);
    } else if (err instanceof KubeMQError) {
      console.log('KubeMQError caught:', err.message);
      console.log('  Code:', err.code);
    } else {
      console.log('Unexpected error:', (err as Error).message);
    }
  }

  // --- Scenario 3: Authentication failure ---
  console.log('\n=== Scenario 3: Authentication Failure (simulated) ===');
  try {
    // This will fail at connection level since server is not running,
    // but demonstrates the pattern for catching auth errors.
    await KubeMQClient.create({
      address: 'localhost:59999',
      clientId: 'js-error-handling-connection-error-auth-client',
      credentials: 'invalid-token',
      connectionTimeoutSeconds: 3,
    });
  } catch (err) {
    if (err instanceof AuthenticationError) {
      console.log('AuthenticationError: Invalid credentials');
    } else if (err instanceof ConnectionError) {
      console.log('ConnectionError (expected in demo):', err.message);
    } else {
      console.log('Error:', (err as Error).message);
    }
  }

  console.log('\nAll error scenarios demonstrated');
}

main().catch(console.error);

```

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

* Scenario 1 targets port 59999 (nothing listening) with a 3-second `connectionTimeoutSeconds` — `KubeMQClient.create()` throws `ConnectionError` or `KubeMQTimeoutError` instead of hanging forever.
* Scenario 2 passes an empty `address` string; the SDK's `ConfigurationError` is thrown before any network I/O, with `err.message` describing the invalid field.
* Scenario 3 shows the pattern for `AuthenticationError` — it surfaces during `create()` when the server rejects the token, separate from transport-level connection failures.
* All SDK errors extend `KubeMQError`; check `err.code` for the machine-readable `ErrorCode` constant and `err.isRetryable` to decide whether to retry.

## Related [#related]

* [Node.js SDK Reference](/sdks/nodejs/reference)
* [Graceful Shutdown](/sdks/nodejs/how-to/error-handling/graceful-shutdown)
* [Reconnection](/sdks/nodejs/how-to/error-handling/reconnection)
