or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

command-execution.mdconfiguration.mddevice-connection.mdexceptions.mdfacts.mdfilesystem.mdindex.mdoperational-tables.mdsoftware.md

exceptions.mddocs/

0

# Exception Handling

1

2

Comprehensive exception hierarchy for handling all types of errors including connection failures, RPC errors, configuration problems, operational issues, and data processing errors. Provides structured error handling with detailed error information and recovery guidance.

3

4

## Capabilities

5

6

### Base Exception Classes

7

8

Foundation exception classes that provide the basis for all junos-eznc specific exceptions.

9

10

```python { .api }

11

class RpcError(Exception):

12

"""

13

Base class for RPC-related exceptions.

14

15

Attributes:

16

- message (str): Error message

17

- rpc_error (dict): Detailed RPC error information

18

- cmd (str): RPC command that failed

19

- rsp (Element): RPC response XML element

20

"""

21

22

def __init__(self, cmd=None, rsp=None, errs=None, dev=None, timeout=None, re=None):

23

"""

24

Initialize RPC error.

25

26

Parameters:

27

- cmd: RPC command that failed

28

- rsp: RPC response element

29

- errs: Error list

30

- dev: Device object

31

- timeout: RPC timeout value

32

- re: Routing engine identifier

33

"""

34

35

class ConnectError(Exception):

36

"""

37

Base class for connection-related exceptions.

38

39

Attributes:

40

- dev (Device): Device object that failed to connect

41

- msg (str): Error message

42

"""

43

44

def __init__(self, dev, msg=None):

45

"""

46

Initialize connection error.

47

48

Parameters:

49

- dev (Device): Device object

50

- msg (str): Error message

51

"""

52

53

class FactLoopError(Exception):

54

"""

55

Exception for fact gathering infinite loops.

56

57

Raised when fact gathering encounters circular dependencies

58

or infinite loops during device fact collection.

59

"""

60

```

61

62

### RPC Exception Classes

63

64

Specific exceptions for RPC operation failures including configuration errors, timeout issues, and operational problems.

65

66

```python { .api }

67

class CommitError(RpcError):

68

"""

69

Configuration commit operation errors.

70

71

Raised when configuration commit operations fail due to

72

validation errors, conflicts, or system issues.

73

"""

74

75

class ConfigLoadError(RpcError):

76

"""

77

Configuration load operation errors.

78

79

Raised when loading configuration data fails due to

80

syntax errors, invalid configurations, or load conflicts.

81

"""

82

83

class LockError(RpcError):

84

"""

85

Configuration lock operation errors.

86

87

Raised when attempting to lock configuration database

88

that is already locked by another user or session.

89

"""

90

91

class UnlockError(RpcError):

92

"""

93

Configuration unlock operation errors.

94

95

Raised when attempting to unlock configuration database

96

fails or when database is not locked.

97

"""

98

99

class PermissionError(RpcError):

100

"""

101

Permission denied errors.

102

103

Raised when user lacks sufficient privileges to perform

104

the requested operation.

105

"""

106

107

class RpcTimeoutError(RpcError):

108

"""

109

RPC operation timeout errors.

110

111

Raised when RPC operations exceed configured timeout

112

values during execution.

113

"""

114

115

class SwRollbackError(RpcError):

116

"""

117

Software rollback operation errors.

118

119

Raised when software installation fails and automatic

120

rollback operations encounter problems.

121

"""

122

```

123

124

### Connection Exception Classes

125

126

Specific exceptions for connection establishment and management failures.

127

128

```python { .api }

129

class ProbeError(ConnectError):

130

"""

131

Device probe operation failures.

132

133

Raised when device connectivity probing fails to

134

reach the target device.

135

"""

136

137

class ConnectAuthError(ConnectError):

138

"""

139

Authentication failures during connection.

140

141

Raised when authentication fails due to invalid

142

credentials or authentication method issues.

143

"""

144

145

class ConnectTimeoutError(ConnectError):

146

"""

147

Connection timeout errors.

148

149

Raised when connection establishment exceeds the

150

configured timeout period.

151

"""

152

153

class ConnectUnknownHostError(ConnectError):

154

"""

155

Unknown host resolution errors.

156

157

Raised when hostname resolution fails or the

158

target host cannot be found.

159

"""

160

161

class ConnectRefusedError(ConnectError):

162

"""

163

Connection refused by target.

164

165

Raised when the target device actively refuses

166

the connection attempt.

167

"""

168

169

class ConnectNotMasterError(ConnectError):

170

"""

171

Connection not to master routing engine.

172

173

Raised when connection is established to backup

174

routing engine but master was expected.

175

"""

176

177

class ConnectClosedError(ConnectError):

178

"""

179

Unexpected connection closure.

180

181

Raised when connection is unexpectedly closed

182

during operation.

183

"""

184

```

185

186

### Data Processing Exception Classes

187

188

Exceptions for data parsing, processing, and format conversion errors.

189

190

```python { .api }

191

class JSONLoadError(Exception):

192

"""

193

JSON parsing and loading errors.

194

195

Raised when JSON data parsing fails due to invalid

196

JSON format or structure issues.

197

198

Attributes:

199

- data (str): JSON data that failed to parse

200

- message (str): Error message

201

"""

202

203

def __init__(self, data, message):

204

"""

205

Initialize JSON load error.

206

207

Parameters:

208

- data (str): JSON data that failed

209

- message (str): Error description

210

"""

211

```

212

213

## Usage Examples

214

215

### Basic Exception Handling

216

217

```python

218

from jnpr.junos import Device

219

from jnpr.junos.exception import ConnectError, RpcError

220

221

dev = Device(host='router1.example.com', user='admin', passwd='secret')

222

223

try:

224

dev.open()

225

result = dev.cli('show version')

226

print(result)

227

228

except ConnectError as e:

229

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

230

231

except RpcError as e:

232

print(f"RPC operation failed: {e}")

233

234

finally:

235

if dev.connected:

236

dev.close()

237

```

238

239

### Specific Connection Error Handling

240

241

```python

242

from jnpr.junos import Device

243

from jnpr.junos.exception import (

244

ConnectAuthError, ConnectTimeoutError, ConnectUnknownHostError,

245

ConnectRefusedError, ProbeError

246

)

247

248

dev = Device(host='router1.example.com', user='admin', passwd='secret')

249

250

try:

251

# Test connectivity first

252

if dev.probe(timeout=10):

253

dev.open()

254

print("Connected successfully")

255

else:

256

print("Device is not reachable")

257

258

except ConnectAuthError:

259

print("Authentication failed - check username/password")

260

261

except ConnectTimeoutError:

262

print("Connection timed out - device may be unreachable")

263

264

except ConnectUnknownHostError:

265

print("Unknown host - check hostname/IP address")

266

267

except ConnectRefusedError:

268

print("Connection refused - check NETCONF service status")

269

270

except ProbeError:

271

print("Probe failed - network connectivity issues")

272

273

except ConnectError as e:

274

print(f"General connection error: {e}")

275

```

276

277

### Configuration Error Handling

278

279

```python

280

from jnpr.junos import Device

281

from jnpr.junos.utils.config import Config

282

from jnpr.junos.exception import (

283

ConfigLoadError, CommitError, LockError, UnlockError

284

)

285

286

dev = Device(host='router1.example.com', user='admin', passwd='secret')

287

dev.open()

288

dev.bind(cu=Config)

289

290

try:

291

# Lock configuration

292

dev.cu.lock()

293

294

# Load configuration

295

config = 'set interfaces ge-0/0/0 description "Test Interface"'

296

dev.cu.load(config, format='set')

297

298

# Commit configuration

299

dev.cu.commit(comment='Test configuration change')

300

print("Configuration committed successfully")

301

302

except LockError as e:

303

print(f"Configuration lock failed: {e}")

304

print("Database may be locked by another user")

305

306

except ConfigLoadError as e:

307

print(f"Configuration load error: {e}")

308

print("Check configuration syntax and validity")

309

310

except CommitError as e:

311

print(f"Configuration commit failed: {e}")

312

print("Detailed error information:")

313

if hasattr(e, 'rpc_error'):

314

for error in e.rpc_error:

315

print(f" - {error}")

316

317

except UnlockError:

318

print("Failed to unlock configuration database")

319

320

finally:

321

# Always attempt to unlock

322

try:

323

dev.cu.unlock()

324

except:

325

pass

326

327

dev.close()

328

```

329

330

### RPC Timeout Handling

331

332

```python

333

from jnpr.junos import Device

334

from jnpr.junos.exception import RpcTimeoutError, RpcError

335

336

dev = Device(host='router1.example.com', user='admin', passwd='secret')

337

dev.open()

338

339

# Set device-wide timeout

340

dev.timeout = 60

341

342

try:

343

# Execute potentially long-running command

344

result = dev.cli('show route extensive', dev_timeout=120)

345

print("Command completed successfully")

346

347

except RpcTimeoutError:

348

print("Command timed out after 120 seconds")

349

print("Consider increasing timeout or using background processing")

350

351

except RpcError as e:

352

print(f"RPC error: {e}")

353

if hasattr(e, 'message'):

354

print(f"Error message: {e.message}")

355

356

dev.close()

357

```

358

359

### Software Management Error Handling

360

361

```python

362

from jnpr.junos import Device

363

from jnpr.junos.utils.sw import SW

364

from jnpr.junos.exception import SwRollbackError, RpcTimeoutError

365

366

dev = Device(host='router1.example.com', user='admin', passwd='secret')

367

dev.open()

368

dev.bind(sw=SW)

369

370

try:

371

# Attempt software installation

372

result = dev.sw.install(

373

package='/path/to/software.tgz',

374

timeout=3600,

375

validate=True

376

)

377

378

if result:

379

print("Software installation successful")

380

dev.sw.reboot()

381

else:

382

print("Software installation failed")

383

384

except SwRollbackError as e:

385

print(f"Installation failed and rollback occurred: {e}")

386

print("Device reverted to previous software version")

387

388

except RpcTimeoutError:

389

print("Software installation timed out")

390

print("Installation may still be in progress")

391

392

except FileNotFoundError:

393

print("Software package file not found")

394

395

except Exception as e:

396

print(f"Unexpected software installation error: {e}")

397

398

dev.close()

399

```

400

401

### JSON Processing Error Handling

402

403

```python

404

from jnpr.junos import Device

405

from jnpr.junos.exception import JSONLoadError

406

import json

407

408

dev = Device(host='router1.example.com', user='admin', passwd='secret')

409

dev.open()

410

411

try:

412

# Get JSON output from device

413

result = dev.cli('show interfaces', format='json')

414

415

# Parse JSON data

416

try:

417

data = json.loads(result)

418

print("JSON parsing successful")

419

420

except json.JSONDecodeError as e:

421

raise JSONLoadError(result, f"Invalid JSON format: {e}")

422

423

except JSONLoadError as e:

424

print(f"JSON processing error: {e.message}")

425

print("Raw data that failed to parse:")

426

print(e.data[:200] + "..." if len(e.data) > 200 else e.data)

427

428

dev.close()

429

```

430

431

### Comprehensive Error Handling

432

433

```python

434

from jnpr.junos import Device

435

from jnpr.junos.utils.config import Config

436

from jnpr.junos.exception import *

437

import logging

438

439

# Configure logging

440

logging.basicConfig(level=logging.INFO)

441

logger = logging.getLogger(__name__)

442

443

def safe_device_operation(hostname, config_data):

444

"""Perform device operations with comprehensive error handling."""

445

dev = None

446

447

try:

448

# Device connection

449

dev = Device(host=hostname, user='admin', passwd='secret')

450

logger.info(f"Connecting to {hostname}")

451

dev.open()

452

453

# Bind utilities

454

dev.bind(cu=Config)

455

456

# Configuration operations

457

logger.info("Loading configuration")

458

dev.cu.lock()

459

dev.cu.load(config_data, format='set')

460

461

# Validate before commit

462

if dev.cu.commit_check():

463

logger.info("Configuration validation passed")

464

dev.cu.commit(comment='Automated configuration update')

465

logger.info("Configuration committed successfully")

466

else:

467

logger.warning("Configuration validation failed")

468

469

except ConnectAuthError:

470

logger.error(f"Authentication failed for {hostname}")

471

return False

472

473

except ConnectTimeoutError:

474

logger.error(f"Connection timeout to {hostname}")

475

return False

476

477

except ConnectError as e:

478

logger.error(f"Connection error to {hostname}: {e}")

479

return False

480

481

except LockError:

482

logger.error(f"Configuration locked on {hostname}")

483

return False

484

485

except ConfigLoadError as e:

486

logger.error(f"Configuration load error on {hostname}: {e}")

487

return False

488

489

except CommitError as e:

490

logger.error(f"Configuration commit error on {hostname}: {e}")

491

return False

492

493

except RpcTimeoutError:

494

logger.error(f"RPC timeout on {hostname}")

495

return False

496

497

except RpcError as e:

498

logger.error(f"RPC error on {hostname}: {e}")

499

return False

500

501

except Exception as e:

502

logger.error(f"Unexpected error on {hostname}: {e}")

503

return False

504

505

finally:

506

if dev:

507

try:

508

# Cleanup operations

509

if hasattr(dev, 'cu'):

510

dev.cu.unlock()

511

if dev.connected:

512

dev.close()

513

logger.info(f"Disconnected from {hostname}")

514

except:

515

pass

516

517

return True

518

519

# Usage

520

config = 'set system location building "Data Center 1"'

521

success = safe_device_operation('router1.example.com', config)

522

```

523

524

### Custom Exception Handling

525

526

```python

527

from jnpr.junos import Device

528

from jnpr.junos.exception import RpcError, ConnectError

529

530

class DeviceOperationError(Exception):

531

"""Custom exception for device operations."""

532

533

def __init__(self, device, operation, original_error):

534

self.device = device

535

self.operation = operation

536

self.original_error = original_error

537

super().__init__(f"Operation '{operation}' failed on {device}: {original_error}")

538

539

def robust_device_operation(hostname, operation_func):

540

"""Wrapper for device operations with custom error handling."""

541

dev = Device(host=hostname, user='admin', passwd='secret')

542

543

try:

544

dev.open()

545

result = operation_func(dev)

546

return result

547

548

except (ConnectError, RpcError) as e:

549

raise DeviceOperationError(hostname, operation_func.__name__, e)

550

551

finally:

552

if dev.connected:

553

dev.close()

554

555

# Usage

556

def get_version_info(dev):

557

return dev.cli('show version')

558

559

try:

560

version = robust_device_operation('router1.example.com', get_version_info)

561

print(version)

562

563

except DeviceOperationError as e:

564

print(f"Custom error: {e}")

565

print(f"Device: {e.device}")

566

print(f"Operation: {e.operation}")

567

print(f"Original error: {e.original_error}")

568

```

569

570

## Types

571

572

```python { .api }

573

# Exception base types

574

JunosException = Exception # Base for all junos-eznc exceptions

575

ErrorMessage = str # Error message string

576

ErrorCode = int # Numeric error code

577

578

# RPC error details

579

RpcErrorDict = dict[str, any] # RPC error information dictionary

580

RpcResponse = object # RPC response XML element

581

582

# Connection error details

583

DeviceRef = object # Reference to Device object

584

HostInfo = str # Hostname or IP address

585

586

# Error context information

587

ErrorContext = dict[str, any] # Additional error context data

588

```