0
# Error Handling
1
2
Comprehensive exception hierarchy for different error conditions including connection failures, protocol errors, timeout situations, and controller registration issues. PyChromecast provides specific exception types to help applications handle different failure scenarios appropriately.
3
4
## Capabilities
5
6
### Exception Hierarchy
7
8
PyChromecast defines a structured exception hierarchy for different types of errors.
9
10
```python { .api }
11
class PyChromecastError(Exception):
12
"""Base error for PyChromecast."""
13
14
class ChromecastConnectionError(PyChromecastError):
15
"""When a connection error occurs within PyChromecast."""
16
17
class PyChromecastStopped(PyChromecastError):
18
"""
19
Raised when a command is invoked while the Chromecast's socket_client is stopped.
20
"""
21
22
class NotConnected(PyChromecastError):
23
"""
24
Raised when a command is invoked while not connected to a Chromecast.
25
"""
26
27
class UnsupportedNamespace(PyChromecastError):
28
"""
29
Raised when trying to send a message with a namespace that is not
30
supported by the current running app.
31
"""
32
33
class ControllerNotRegistered(PyChromecastError):
34
"""
35
Raised when trying to interact with a controller while it is
36
not registered with a ChromeCast object.
37
"""
38
39
class RequestFailed(PyChromecastError):
40
"""
41
Raised when a request failed to complete.
42
43
Attributes:
44
- request: str, Description of the failed request
45
"""
46
def __init__(self, request: str): ...
47
48
class RequestTimeout(PyChromecastError):
49
"""
50
Raised when a request timed out.
51
52
Attributes:
53
- request: str, Description of the timed out request
54
- timeout: float, Timeout value that was exceeded
55
"""
56
def __init__(self, request: str, timeout: float): ...
57
58
class ZeroConfInstanceRequired(PyChromecastError):
59
"""Raised when a zeroconf instance is required."""
60
```
61
62
### Connection Error Handling
63
64
Handle connection-related errors during device discovery and communication.
65
66
**Usage Example:**
67
68
```python
69
import pychromecast
70
from pychromecast.error import (
71
ChromecastConnectionError,
72
NotConnected,
73
PyChromecastStopped
74
)
75
76
try:
77
# Attempt to discover devices
78
chromecasts, browser = pychromecast.get_chromecasts()
79
80
if not chromecasts:
81
print("No Chromecast devices found")
82
return
83
84
cast = chromecasts[0]
85
86
try:
87
# Wait for connection
88
cast.wait(timeout=10.0)
89
print(f"Connected to {cast.name}")
90
91
except pychromecast.RequestTimeout as e:
92
print(f"Connection timeout: {e}")
93
94
except NotConnected as e:
95
print(f"Not connected to device: {e}")
96
97
except ChromecastConnectionError as e:
98
print(f"Connection error: {e}")
99
100
except Exception as e:
101
print(f"Unexpected error: {e}")
102
103
finally:
104
# Always stop discovery
105
if 'browser' in locals():
106
browser.stop_discovery()
107
```
108
109
### Request Error Handling
110
111
Handle request failures and timeouts during device operations.
112
113
**Usage Example:**
114
115
```python
116
from pychromecast.error import RequestFailed, RequestTimeout
117
118
try:
119
# Attempt to start an app
120
cast.start_app(pychromecast.APP_YOUTUBE, timeout=30.0)
121
122
# Attempt to play media
123
cast.media_controller.play_media(
124
"http://example.com/video.mp4",
125
"video/mp4"
126
)
127
128
# Wait for media to become active
129
cast.media_controller.block_until_active(timeout=15.0)
130
131
except RequestTimeout as e:
132
print(f"Request timed out: {e}")
133
print(f"Timeout was: {e.timeout} seconds")
134
135
except RequestFailed as e:
136
print(f"Request failed: {e}")
137
138
except NotConnected:
139
print("Device is not connected")
140
141
except PyChromecastStopped:
142
print("Chromecast connection has been stopped")
143
```
144
145
### Controller Error Handling
146
147
Handle controller-specific errors including unsupported operations and registration issues.
148
149
**Usage Example:**
150
151
```python
152
from pychromecast.error import (
153
ControllerNotRegistered,
154
UnsupportedNamespace,
155
ZeroConfInstanceRequired
156
)
157
from pychromecast.controllers.youtube import YouTubeController
158
159
try:
160
# Create controller
161
yt_controller = YouTubeController()
162
163
# This will fail - controller not registered yet
164
yt_controller.play_video("dQw4w9WgXcQ")
165
166
except ControllerNotRegistered as e:
167
print(f"Controller not registered: {e}")
168
169
# Register the controller
170
cast.register_handler(yt_controller)
171
172
try:
173
# Launch YouTube app
174
yt_controller.launch()
175
176
# Now this should work
177
yt_controller.play_video("dQw4w9WgXcQ")
178
179
except UnsupportedNamespace as e:
180
print(f"Namespace not supported by current app: {e}")
181
182
except RequestTimeout as e:
183
print(f"YouTube operation timed out: {e}")
184
185
except ZeroConfInstanceRequired as e:
186
print(f"ZeroConf instance required for this operation: {e}")
187
```
188
189
### Volume Control Error Handling
190
191
Handle volume control specific errors.
192
193
**Usage Example:**
194
195
```python
196
try:
197
# Attempt volume control
198
current_volume = cast.status.volume_level if cast.status else 0.0
199
200
# Try to increase volume
201
new_volume = cast.volume_up(delta=0.2, timeout=10.0)
202
print(f"Volume changed from {current_volume:.1f} to {new_volume:.1f}")
203
204
except ValueError as e:
205
print(f"Invalid volume delta: {e}")
206
207
except NotConnected as e:
208
print(f"Cannot control volume - not connected: {e}")
209
210
except RequestTimeout as e:
211
print(f"Volume control timed out: {e}")
212
```
213
214
### Media Control Error Handling
215
216
Handle media-specific errors during playback operations.
217
218
**Usage Example:**
219
220
```python
221
try:
222
media_ctrl = cast.media_controller
223
224
# Try to play media
225
media_ctrl.play_media(
226
"https://example.com/video.mp4",
227
"video/mp4",
228
title="Test Video"
229
)
230
231
# Wait for media to load
232
media_ctrl.block_until_active(timeout=30.0)
233
234
# Control playback
235
media_ctrl.pause()
236
media_ctrl.seek(60.0) # Seek to 1 minute
237
media_ctrl.play()
238
239
except RequestTimeout as e:
240
print(f"Media operation timed out: {e}")
241
if "block_until_active" in str(e):
242
print("Media failed to load within timeout")
243
244
except UnsupportedNamespace as e:
245
print(f"Media namespace not supported: {e}")
246
# May need to launch media receiver app first
247
cast.start_app(pychromecast.APP_MEDIA_RECEIVER)
248
249
except NotConnected as e:
250
print(f"Cannot control media - not connected: {e}")
251
```
252
253
### Discovery Error Handling
254
255
Handle errors during device discovery process.
256
257
**Usage Example:**
258
259
```python
260
import zeroconf
261
from pychromecast.models import ZEROCONF_ERRORS
262
263
try:
264
# Discovery with custom zeroconf instance
265
zconf = zeroconf.Zeroconf()
266
267
chromecasts, browser = pychromecast.get_chromecasts(
268
zeroconf_instance=zconf,
269
timeout=10.0
270
)
271
272
if not chromecasts:
273
print("No devices discovered")
274
275
except ZEROCONF_ERRORS as e:
276
print(f"ZeroConf error during discovery: {e}")
277
278
except ChromecastConnectionError as e:
279
print(f"Connection error during discovery: {e}")
280
281
except Exception as e:
282
print(f"Unexpected discovery error: {e}")
283
284
finally:
285
# Clean up
286
if 'browser' in locals():
287
browser.stop_discovery()
288
if 'zconf' in locals():
289
zconf.close()
290
```
291
292
### Comprehensive Error Handling Pattern
293
294
A complete error handling pattern for typical PyChromecast usage.
295
296
**Usage Example:**
297
298
```python
299
import pychromecast
300
from pychromecast.error import *
301
import time
302
303
def safe_cast_operation():
304
browser = None
305
cast = None
306
307
try:
308
# Discovery phase
309
print("Discovering Chromecast devices...")
310
chromecasts, browser = pychromecast.get_chromecasts(timeout=10.0)
311
312
if not chromecasts:
313
print("No Chromecast devices found")
314
return False
315
316
cast = chromecasts[0]
317
print(f"Found device: {cast.name}")
318
319
# Connection phase
320
print("Connecting to device...")
321
cast.wait(timeout=15.0)
322
print("Connected successfully")
323
324
# Operation phase
325
print("Playing media...")
326
cast.media_controller.play_media(
327
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
328
"video/mp4",
329
title="Big Buck Bunny"
330
)
331
332
# Wait for media
333
cast.media_controller.block_until_active(timeout=20.0)
334
print("Media is playing")
335
336
# Brief pause then cleanup
337
time.sleep(5)
338
return True
339
340
except RequestTimeout as e:
341
print(f"Operation timed out: {e}")
342
343
except ChromecastConnectionError as e:
344
print(f"Connection error: {e}")
345
346
except NotConnected as e:
347
print(f"Device not connected: {e}")
348
349
except UnsupportedNamespace as e:
350
print(f"Unsupported operation: {e}")
351
352
except PyChromecastError as e:
353
print(f"PyChromecast error: {e}")
354
355
except Exception as e:
356
print(f"Unexpected error: {e}")
357
358
finally:
359
# Cleanup phase
360
if cast:
361
try:
362
cast.disconnect(timeout=5.0)
363
print("Disconnected from device")
364
except Exception as e:
365
print(f"Error during disconnect: {e}")
366
367
if browser:
368
try:
369
browser.stop_discovery()
370
print("Stopped discovery")
371
except Exception as e:
372
print(f"Error stopping discovery: {e}")
373
374
return False
375
376
# Usage
377
success = safe_cast_operation()
378
print(f"Operation {'succeeded' if success else 'failed'}")
379
```
380
381
## Error Categories
382
383
### Network and Connection Errors
384
- `ChromecastConnectionError` - General connection issues
385
- `NotConnected` - Operations attempted without connection
386
- `ZeroConfInstanceRequired` - mDNS operations requiring ZeroConf
387
388
### Request and Protocol Errors
389
- `RequestTimeout` - Operations exceeding time limits
390
- `RequestFailed` - Failed protocol requests
391
- `UnsupportedNamespace` - App doesn't support the operation
392
393
### Controller and State Errors
394
- `ControllerNotRegistered` - Controller operations without registration
395
- `PyChromecastStopped` - Operations on stopped connections
396
397
### Standard Python Errors
398
- `ValueError` - Invalid parameter values (e.g., negative volume delta)
399
- `TimeoutError` - Standard timeout in join operations
400
401
## Best Practices
402
403
1. **Always use try-except blocks** around PyChromecast operations
404
2. **Handle specific exceptions** rather than catching all exceptions
405
3. **Always clean up resources** in finally blocks
406
4. **Check device status** before operations when possible
407
5. **Use appropriate timeouts** for different operations
408
6. **Log errors appropriately** for debugging
409
7. **Provide user feedback** for error conditions