or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-client.mdexceptions.mdhandlers.mdindex.mdrecipes.mdsecurity.mdtesting.md

exceptions.mddocs/

0

# Exception Handling

1

2

Comprehensive exception hierarchy for handling all Zookeeper error conditions, including connection issues, node state conflicts, authentication failures, and protocol errors. Each exception includes appropriate error codes and context information for robust error handling.

3

4

## Capabilities

5

6

### Base Exception Classes

7

8

Foundation exception classes providing the hierarchy for all Kazoo library errors with common error handling patterns and context information.

9

10

```python { .api }

11

class KazooException(Exception):

12

"""Base exception for all Kazoo library exceptions."""

13

14

class ZookeeperError(KazooException):

15

"""

16

Base exception for errors originating from Zookeeper server.

17

18

Attributes:

19

- code (int): Zookeeper error code

20

"""

21

22

class CancelledError(KazooException):

23

"""Raised when a process is cancelled by another thread."""

24

25

class ConfigurationError(KazooException):

26

"""Raised if configuration arguments are invalid."""

27

28

class ZookeeperStoppedError(KazooException):

29

"""Raised when kazoo client is stopped during operation."""

30

31

class ConnectionDropped(KazooException):

32

"""Internal error for jumping out of connection loops."""

33

34

class LockTimeout(KazooException):

35

"""Raised if failed to acquire a lock within timeout."""

36

37

class WriterNotClosedException(KazooException):

38

"""Raised if writer unable to close when requested."""

39

40

class SASLException(KazooException):

41

"""Raised if SASL encountered a local error."""

42

43

```

44

45

### Connection and Session Errors

46

47

Errors related to network connectivity, session management, and client-server communication with specific handling for different failure scenarios.

48

49

```python { .api }

50

class ConnectionLoss(ZookeeperError):

51

"""

52

Connection to server lost (code: -4).

53

54

Raised when network connection is interrupted or server becomes

55

unreachable. Operations may be retried after reconnection.

56

"""

57

58

class SessionExpiredError(ZookeeperError):

59

"""

60

Session expired (code: -112).

61

62

Raised when Zookeeper session expires due to timeout or network

63

issues. Client must reconnect and re-establish watches and ephemeral nodes.

64

"""

65

66

class SessionMovedError(ZookeeperError):

67

"""

68

Session moved to another server (code: -118).

69

70

Raised when session is transferred between servers in the ensemble.

71

"""

72

73

class ConnectionClosedError(ZookeeperError):

74

"""

75

Connection is closed.

76

77

Raised when attempting operations on a closed client connection.

78

"""

79

80

class OperationTimeoutError(ZookeeperError):

81

"""

82

Operation timed out (code: -7).

83

84

Raised when operation exceeds configured timeout period.

85

"""

86

```

87

88

### Node Operation Errors

89

90

Errors specific to node CRUD operations including existence conflicts, version mismatches, and hierarchy violations.

91

92

```python { .api }

93

class NoNodeError(ZookeeperError):

94

"""

95

Node does not exist (code: -101).

96

97

Raised when attempting operations on non-existent nodes.

98

"""

99

100

class NodeExistsError(ZookeeperError):

101

"""

102

Node already exists (code: -110).

103

104

Raised when creating a node that already exists without

105

using sequence or overwrite options.

106

"""

107

108

class BadVersionError(ZookeeperError):

109

"""

110

Version conflict (code: -103).

111

112

Raised when node version doesn't match expected version

113

in conditional operations.

114

"""

115

116

class NotEmptyError(ZookeeperError):

117

"""

118

Node has children (code: -111).

119

120

Raised when attempting to delete a node that has children

121

without using recursive deletion.

122

"""

123

124

class NoChildrenForEphemeralsError(ZookeeperError):

125

"""

126

Ephemeral nodes cannot have children (code: -108).

127

128

Raised when attempting to create children under ephemeral nodes.

129

"""

130

```

131

132

### Authentication and Authorization Errors

133

134

Security-related errors covering authentication failures, authorization denials, and ACL violations with detailed error context.

135

136

```python { .api }

137

class AuthFailedError(ZookeeperError):

138

"""

139

Authentication failed (code: -115).

140

141

Raised when authentication credentials are invalid or

142

authentication scheme is not supported.

143

"""

144

145

class NoAuthError(ZookeeperError):

146

"""

147

Not authenticated (code: -102).

148

149

Raised when attempting operations requiring authentication

150

without proper credentials.

151

"""

152

153

class InvalidACLError(ZookeeperError):

154

"""

155

Invalid ACL (code: -114).

156

157

Raised when ACL format is invalid or contains unsupported

158

permissions or schemes.

159

"""

160

```

161

162

### Protocol and System Errors

163

164

Low-level protocol errors and system-level failures including serialization issues, implementation errors, and server-side problems.

165

166

```python { .api }

167

class SystemZookeeperError(ZookeeperError):

168

"""

169

System error in Zookeeper (code: -1).

170

171

Raised for internal Zookeeper server errors.

172

"""

173

174

class RuntimeInconsistency(ZookeeperError):

175

"""

176

Runtime inconsistency detected (code: -2).

177

178

Raised when Zookeeper detects internal inconsistencies.

179

"""

180

181

class DataInconsistency(ZookeeperError):

182

"""

183

Data inconsistency detected (code: -3).

184

185

Raised when data corruption or inconsistency is detected.

186

"""

187

188

class MarshallingError(ZookeeperError):

189

"""

190

Error marshalling/unmarshalling data (code: -5).

191

192

Raised when serialization or deserialization fails.

193

"""

194

195

class UnimplementedError(ZookeeperError):

196

"""

197

Unimplemented operation (code: -6).

198

199

Raised when attempting unsupported operations.

200

"""

201

202

class BadArgumentsError(ZookeeperError):

203

"""

204

Invalid arguments provided (code: -8).

205

206

Raised when operation parameters are invalid.

207

"""

208

209

class APIError(ZookeeperError):

210

"""

211

General API error (code: -100).

212

213

Raised for general API usage errors.

214

"""

215

216

class InvalidCallbackError(ZookeeperError):

217

"""

218

Invalid callback (code: -113).

219

220

Raised when callback function is invalid or malformed.

221

"""

222

```

223

224

### Transaction and Configuration Errors

225

226

Errors related to atomic transactions, ensemble reconfiguration, and advanced Zookeeper operations with specific error handling requirements.

227

228

```python { .api }

229

class RolledBackError(ZookeeperError):

230

"""

231

Transaction rolled back (code: 0).

232

233

Raised when atomic transaction fails and all operations

234

are rolled back. Contains details of failed operations.

235

"""

236

237

class NewConfigNoQuorumError(ZookeeperError):

238

"""

239

New config has no quorum (code: -13).

240

241

Raised during ensemble reconfiguration when new configuration

242

cannot establish quorum.

243

"""

244

245

class ReconfigInProcessError(ZookeeperError):

246

"""

247

Reconfiguration in process (code: -14).

248

249

Raised when attempting reconfiguration while another

250

reconfiguration is already in progress.

251

"""

252

253

class NotReadOnlyCallError(ZookeeperError):

254

"""

255

Not a read-only call (code: -119).

256

257

Raised when attempting write operations on read-only connections.

258

"""

259

260

class QuotaExceededError(ZookeeperError):

261

"""

262

Quota exceeded (code: -125).

263

264

Raised when operation would exceed configured quotas.

265

"""

266

```

267

268

### Handler-Specific Errors

269

270

Errors specific to different async handler implementations including timeout handling and concurrency management.

271

272

```python { .api }

273

class KazooTimeoutError(Exception):

274

"""

275

Timeout exception for threading handler.

276

277

Raised when operations timeout in threading-based handlers.

278

"""

279

280

class TimeoutError(Exception):

281

"""

282

Timeout exception for eventlet handler.

283

284

Raised when operations timeout in eventlet-based handlers.

285

"""

286

```

287

288

### Error Code Mapping

289

290

Utility for mapping Zookeeper error codes to appropriate exception classes with comprehensive coverage of all protocol errors.

291

292

```python { .api }

293

# Error code constants

294

EXCEPTIONS = {

295

0: RolledBackError,

296

-1: SystemZookeeperError,

297

-2: RuntimeInconsistency,

298

-3: DataInconsistency,

299

-4: ConnectionLoss,

300

-5: MarshallingError,

301

-6: UnimplementedError,

302

-7: OperationTimeoutError,

303

-8: BadArgumentsError,

304

-13: NewConfigNoQuorumError,

305

-14: ReconfigInProcessError,

306

-100: APIError,

307

-101: NoNodeError,

308

-102: NoAuthError,

309

-103: BadVersionError,

310

-108: NoChildrenForEphemeralsError,

311

-110: NodeExistsError,

312

-111: NotEmptyError,

313

-112: SessionExpiredError,

314

-113: InvalidCallbackError,

315

-114: InvalidACLError,

316

-115: AuthFailedError,

317

-118: SessionMovedError,

318

-119: NotReadOnlyCallError,

319

-125: QuotaExceededError

320

}

321

322

```

323

324

## Retry Exceptions

325

326

The following exceptions are available from `kazoo.retry` module for handling retry logic:

327

328

```python { .api }

329

from kazoo.retry import ForceRetryError, RetryFailedError, InterruptedError

330

331

class ForceRetryError(Exception):

332

"""Raised when recipe logic wants to force a retry."""

333

334

class RetryFailedError(KazooException):

335

"""Raised when retrying ultimately failed."""

336

337

class InterruptedError(RetryFailedError):

338

"""Raised when retry is forcibly interrupted."""

339

```

340

341

## Usage Examples

342

343

### Basic Exception Handling

344

345

```python

346

from kazoo.client import KazooClient

347

from kazoo.exceptions import (

348

NoNodeError, NodeExistsError, ConnectionLoss,

349

SessionExpiredError, AuthFailedError

350

)

351

352

zk = KazooClient()

353

354

try:

355

zk.start(timeout=10)

356

357

# Handle node existence

358

try:

359

data, stat = zk.get("/nonexistent")

360

except NoNodeError:

361

print("Node does not exist, creating it...")

362

zk.create("/nonexistent", b"data", makepath=True)

363

364

# Handle node creation conflicts

365

try:

366

zk.create("/existing", b"data")

367

except NodeExistsError:

368

print("Node already exists, updating instead...")

369

zk.set("/existing", b"new data")

370

371

except ConnectionLoss:

372

print("Connection lost, retrying...")

373

# Implement retry logic

374

except SessionExpiredError:

375

print("Session expired, reconnecting...")

376

zk.restart()

377

except AuthFailedError:

378

print("Authentication failed, check credentials")

379

finally:

380

if zk.connected:

381

zk.stop()

382

```

383

384

### Transaction Error Handling

385

386

```python

387

from kazoo.client import KazooClient

388

from kazoo.exceptions import RolledBackError, BadVersionError

389

390

zk = KazooClient()

391

zk.start()

392

393

try:

394

# Create transaction with error handling

395

transaction = zk.transaction()

396

transaction.create("/app/counter", b"0")

397

transaction.create("/app/status", b"active")

398

transaction.check("/app", version=0)

399

400

try:

401

results = transaction.commit()

402

print("Transaction successful")

403

except RolledBackError as e:

404

print(f"Transaction failed: {e}")

405

# Handle rollback - examine which operations failed

406

407

except BadVersionError:

408

print("Version mismatch in transaction")

409

# Handle version conflicts

410

finally:

411

zk.stop()

412

```

413

414

### Connection State Monitoring

415

416

```python

417

from kazoo.client import KazooClient

418

from kazoo.protocol.states import KazooState

419

from kazoo.exceptions import ConnectionLoss, SessionExpiredError

420

421

def connection_listener(state):

422

if state == KazooState.LOST:

423

print("Connection lost!")

424

elif state == KazooState.SUSPENDED:

425

print("Connection suspended")

426

elif state == KazooState.CONNECTED:

427

print("Connected to Zookeeper")

428

429

zk = KazooClient()

430

zk.add_listener(connection_listener)

431

432

try:

433

zk.start()

434

435

# Monitor for connection issues during operations

436

while True:

437

try:

438

# Perform operations

439

data, stat = zk.get("/some/path")

440

# Process data

441

442

except ConnectionLoss:

443

print("Connection lost during operation")

444

# Wait for reconnection or retry

445

zk.retry(lambda: zk.get("/some/path"))

446

447

except SessionExpiredError:

448

print("Session expired, restarting client")

449

zk.restart()

450

# Re-establish watches and ephemeral nodes

451

452

except KeyboardInterrupt:

453

print("Shutting down...")

454

finally:

455

zk.stop()

456

```

457

458

### Retry Pattern with Exception Handling

459

460

```python

461

from kazoo.client import KazooClient

462

from kazoo.retry import KazooRetry

463

from kazoo.exceptions import ConnectionLoss, OperationTimeoutError

464

import time

465

466

zk = KazooClient()

467

zk.start()

468

469

# Create retry policy

470

retry = KazooRetry(max_tries=3, delay=1, backoff=2)

471

472

def safe_operation():

473

"""Operation with comprehensive error handling."""

474

try:

475

# Attempt operation with retry

476

result = retry(zk.get, "/important/data")

477

return result

478

479

except ConnectionLoss:

480

print("Connection issues, operation failed after retries")

481

return None

482

483

except OperationTimeoutError:

484

print("Operation timed out after retries")

485

return None

486

487

except Exception as e:

488

print(f"Unexpected error: {type(e).__name__}: {e}")

489

return None

490

491

try:

492

result = safe_operation()

493

if result:

494

data, stat = result

495

print(f"Got data: {data}")

496

else:

497

print("Operation failed")

498

499

finally:

500

zk.stop()

501

```