0
# Exception Handling
1
2
Rich exception hierarchy providing detailed error information for different failure modes including network errors, extraction failures, post-processing issues, and user interaction problems. The exception system enables precise error handling and recovery strategies.
3
4
## Capabilities
5
6
### Base Exception Classes
7
8
Core exception hierarchy providing foundation for all yt-dlp error conditions.
9
10
```python { .api }
11
class YoutubeDLError(Exception):
12
"""
13
Base exception class for all yt-dlp errors.
14
15
Provides common functionality for error messages,
16
context information, and error categorization.
17
"""
18
19
def __init__(self, msg=None):
20
"""
21
Initialize base yt-dlp exception.
22
23
Parameters:
24
- msg: str|None, error message
25
"""
26
27
class UnsupportedError(YoutubeDLError):
28
"""
29
Exception for unsupported operations or content.
30
31
Raised when attempting operations not supported
32
by the current context or configuration.
33
"""
34
35
class RegexNotFoundError(UnsupportedError):
36
"""
37
Exception for regex pattern matching failures.
38
39
Raised when required regex patterns don't match
40
expected content during extraction.
41
"""
42
43
class GeoRestrictedError(UnsupportedError):
44
"""
45
Exception for geographically restricted content.
46
47
Indicates content is not available in the current
48
geographic location due to regional restrictions.
49
"""
50
51
def __init__(self, msg, countries=None, **kwargs):
52
"""
53
Initialize geo-restriction exception.
54
55
Parameters:
56
- msg: str, error message
57
- countries: list[str]|None, allowed countries
58
- **kwargs: additional context information
59
"""
60
```
61
62
### Extraction Errors
63
64
Exceptions related to information extraction and site-specific processing.
65
66
```python { .api }
67
class ExtractorError(YoutubeDLError):
68
"""
69
Exception for extractor operation failures.
70
71
Raised when extractors encounter problems parsing
72
content, accessing APIs, or processing responses.
73
"""
74
75
def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None, ie=None):
76
"""
77
Initialize extractor error.
78
79
Parameters:
80
- msg: str, error message
81
- tb: str|None, traceback information
82
- expected: bool, whether error was expected
83
- cause: Exception|None, underlying cause
84
- video_id: str|None, video identifier
85
- ie: str|None, extractor name
86
"""
87
88
class UnsupportedURLIE(ExtractorError):
89
"""
90
Exception for unsupported URL patterns.
91
92
Raised when no extractor can handle the provided URL
93
or when URL format is not recognized.
94
"""
95
96
class LoginRequiredError(ExtractorError):
97
"""
98
Exception indicating authentication is required.
99
100
Raised when content requires login credentials
101
that were not provided or are invalid.
102
"""
103
104
class PrivateVideoError(ExtractorError):
105
"""
106
Exception for private or restricted videos.
107
108
Raised when attempting to access private content
109
without proper authorization or permissions.
110
"""
111
112
class ContentTooShortError(YoutubeDLError):
113
"""
114
Exception for incomplete downloads.
115
116
Raised when downloaded content is shorter than
117
expected based on Content-Length headers.
118
"""
119
120
def __init__(self, downloaded, expected):
121
"""
122
Initialize content length error.
123
124
Parameters:
125
- downloaded: int, bytes downloaded
126
- expected: int, expected bytes
127
"""
128
```
129
130
### Download Errors
131
132
Exceptions related to file downloading and network operations.
133
134
```python { .api }
135
class DownloadError(YoutubeDLError):
136
"""
137
Exception for download operation failures.
138
139
Raised when file downloads fail due to network issues,
140
server errors, or file system problems.
141
"""
142
143
def __init__(self, msg, exc_info=None):
144
"""
145
Initialize download error.
146
147
Parameters:
148
- msg: str, error message
149
- exc_info: tuple|None, exception information
150
"""
151
152
class DownloadCancelled(YoutubeDLError):
153
"""
154
Exception for user-cancelled downloads.
155
156
Raised when downloads are interrupted by user
157
action such as Ctrl+C or explicit cancellation.
158
"""
159
160
class MaxDownloadsReached(DownloadError):
161
"""
162
Exception when maximum download limit is reached.
163
164
Raised when the configured maximum number of
165
downloads has been completed.
166
"""
167
168
class SameFileError(YoutubeDLError):
169
"""
170
Exception for file conflict errors.
171
172
Raised when attempting to write to a file that
173
would conflict with existing files or operations.
174
"""
175
176
def __init__(self, filename):
177
"""
178
Initialize file conflict error.
179
180
Parameters:
181
- filename: str, conflicting filename
182
"""
183
184
class ExistingVideoReached(DownloadError):
185
"""
186
Exception when encountering existing video in archive.
187
188
Raised when break_on_existing is enabled and
189
a video already exists in the download archive.
190
"""
191
192
class RejectedVideoReached(DownloadError):
193
"""
194
Exception when video is rejected by filters.
195
196
Raised when break_on_reject is enabled and
197
a video is rejected by match filters.
198
"""
199
```
200
201
### Post-Processing Errors
202
203
Exceptions related to post-processing operations and file transformations.
204
205
```python { .api }
206
class PostProcessingError(YoutubeDLError):
207
"""
208
Exception for post-processing failures.
209
210
Raised when post-processors encounter errors during
211
file processing, conversion, or transformation.
212
"""
213
214
def __init__(self, msg):
215
"""
216
Initialize post-processing error.
217
218
Parameters:
219
- msg: str, error message
220
"""
221
```
222
223
### Network and Authentication Errors
224
225
Exceptions related to network connectivity, authentication, and cookie handling.
226
227
```python { .api }
228
class CookieLoadError(YoutubeDLError):
229
"""
230
Exception for cookie loading failures.
231
232
Raised when cookies cannot be loaded from browsers,
233
files, or other sources due to access or format issues.
234
"""
235
236
class HTTPError(YoutubeDLError):
237
"""
238
Exception for HTTP response errors.
239
240
Raised when HTTP requests receive error status codes
241
or encounter network-related problems.
242
"""
243
244
def __init__(self, status_code, response_data=None):
245
"""
246
Initialize HTTP error.
247
248
Parameters:
249
- status_code: int, HTTP status code
250
- response_data: str|None, response content
251
"""
252
253
class RequestError(YoutubeDLError):
254
"""
255
Exception for request processing errors.
256
257
Raised when HTTP requests fail due to network issues,
258
timeouts, or connection problems.
259
"""
260
261
class SSLError(RequestError):
262
"""
263
Exception for SSL/TLS connection errors.
264
265
Raised when secure connections fail due to certificate
266
issues or SSL/TLS protocol problems.
267
"""
268
269
class NoSupportingHandlers(RequestError):
270
"""
271
Exception when no request handler is available.
272
273
Raised when no network backend can handle the
274
requested URL scheme or protocol.
275
"""
276
```
277
278
### Playlist and Entry Errors
279
280
Exceptions related to playlist processing and entry management.
281
282
```python { .api }
283
class EntryNotInPlaylist(YoutubeDLError):
284
"""
285
Exception when playlist entry is not found.
286
287
Raised when attempting to access playlist entries
288
that don't exist or are out of range.
289
"""
290
291
class ReExtractInfo(YoutubeDLError):
292
"""
293
Exception requesting information re-extraction.
294
295
Special exception used internally to signal that
296
information extraction should be retried.
297
"""
298
```
299
300
### Utility and Processing Errors
301
302
Exceptions from utility functions and specialized processing operations.
303
304
```python { .api }
305
class _UnsafeExtensionError(Exception):
306
"""
307
Exception for unsafe file extensions.
308
309
Raised when file extensions are deemed unsafe
310
for security reasons unless explicitly allowed.
311
"""
312
313
@staticmethod
314
def sanitize_extension(ext, prepend=False):
315
"""
316
Sanitize file extension for safety.
317
318
Parameters:
319
- ext: str, file extension
320
- prepend: bool, prepend dot if missing
321
322
Returns:
323
str: sanitized extension
324
325
Raises:
326
_UnsafeExtensionError: if extension is unsafe
327
"""
328
```
329
330
## Usage Examples
331
332
### Basic Exception Handling
333
334
```python
335
import yt_dlp
336
from yt_dlp.utils import DownloadError, ExtractorError
337
338
try:
339
with yt_dlp.YoutubeDL() as ydl:
340
ydl.download(['https://www.example.com/video'])
341
except DownloadError as e:
342
print(f"Download failed: {e}")
343
except ExtractorError as e:
344
print(f"Extraction failed: {e}")
345
except yt_dlp.utils.YoutubeDLError as e:
346
print(f"General yt-dlp error: {e}")
347
```
348
349
### Specific Error Handling
350
351
```python
352
import yt_dlp
353
from yt_dlp.utils import (
354
GeoRestrictedError, LoginRequiredError,
355
PrivateVideoError, UnsupportedURLIE
356
)
357
358
urls = ['https://www.youtube.com/watch?v=example']
359
360
try:
361
with yt_dlp.YoutubeDL() as ydl:
362
ydl.download(urls)
363
364
except GeoRestrictedError as e:
365
print(f"Content geo-restricted: {e}")
366
print(f"Available in countries: {e.countries}")
367
368
except LoginRequiredError as e:
369
print(f"Login required: {e}")
370
print("Please provide credentials using --username and --password")
371
372
except PrivateVideoError as e:
373
print(f"Private video: {e}")
374
375
except UnsupportedURLIE as e:
376
print(f"Unsupported URL: {e}")
377
378
except ExtractorError as e:
379
print(f"Extractor error: {e}")
380
if e.video_id:
381
print(f"Video ID: {e.video_id}")
382
if e.ie:
383
print(f"Extractor: {e.ie}")
384
```
385
386
### Network Error Handling
387
388
```python
389
import yt_dlp
390
from yt_dlp.networking.exceptions import HTTPError, SSLError, RequestError
391
392
try:
393
with yt_dlp.YoutubeDL() as ydl:
394
ydl.download(['https://www.youtube.com/watch?v=example'])
395
396
except HTTPError as e:
397
print(f"HTTP error {e.status_code}: {e}")
398
399
except SSLError as e:
400
print(f"SSL/TLS error: {e}")
401
print("Try using --no-check-certificate if the certificate is self-signed")
402
403
except RequestError as e:
404
print(f"Network error: {e}")
405
406
except ConnectionError as e:
407
print(f"Connection failed: {e}")
408
```
409
410
### Post-Processing Error Handling
411
412
```python
413
import yt_dlp
414
from yt_dlp.utils import PostProcessingError
415
416
ydl_opts = {
417
'postprocessors': [{
418
'key': 'FFmpegExtractAudio',
419
'preferredcodec': 'mp3',
420
}],
421
}
422
423
try:
424
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
425
ydl.download(['https://www.youtube.com/watch?v=example'])
426
427
except PostProcessingError as e:
428
print(f"Post-processing failed: {e}")
429
print("Check that FFmpeg is installed and accessible")
430
```
431
432
### Download Interruption Handling
433
434
```python
435
import yt_dlp
436
from yt_dlp.utils import (
437
DownloadCancelled, MaxDownloadsReached,
438
ExistingVideoReached, RejectedVideoReached
439
)
440
441
ydl_opts = {
442
'max_downloads': 5,
443
'break_on_existing': True,
444
'download_archive': 'archive.txt',
445
}
446
447
try:
448
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
449
ydl.download(['https://www.youtube.com/playlist?list=example'])
450
451
except DownloadCancelled:
452
print("Download cancelled by user")
453
454
except MaxDownloadsReached:
455
print("Maximum download limit reached")
456
457
except ExistingVideoReached:
458
print("Stopped at existing video (already in archive)")
459
460
except RejectedVideoReached:
461
print("Stopped at rejected video (filtered out)")
462
```
463
464
### Comprehensive Error Handler
465
466
```python
467
import yt_dlp
468
import sys
469
from yt_dlp.utils import YoutubeDLError
470
471
def safe_download(urls, options=None):
472
"""
473
Safely download URLs with comprehensive error handling.
474
475
Parameters:
476
- urls: list[str], URLs to download
477
- options: dict|None, yt-dlp options
478
479
Returns:
480
bool: True if successful, False otherwise
481
"""
482
if options is None:
483
options = {}
484
485
try:
486
with yt_dlp.YoutubeDL(options) as ydl:
487
ydl.download(urls)
488
return True
489
490
except KeyboardInterrupt:
491
print("\nDownload interrupted by user")
492
return False
493
494
except YoutubeDLError as e:
495
print(f"yt-dlp error: {e}")
496
return False
497
498
except Exception as e:
499
print(f"Unexpected error: {e}")
500
return False
501
502
# Usage
503
urls = ['https://www.youtube.com/watch?v=example']
504
success = safe_download(urls, {'format': 'best[height<=720]'})
505
506
if not success:
507
sys.exit(1)
508
```
509
510
### Custom Exception Handling
511
512
```python
513
import yt_dlp
514
from yt_dlp.utils import YoutubeDLError
515
516
class CustomDownloadError(YoutubeDLError):
517
"""Custom exception for application-specific errors."""
518
pass
519
520
def download_with_retry(urls, max_retries=3):
521
"""
522
Download with retry logic and custom error handling.
523
524
Parameters:
525
- urls: list[str], URLs to download
526
- max_retries: int, maximum retry attempts
527
528
Raises:
529
CustomDownloadError: if all retries fail
530
"""
531
for attempt in range(max_retries + 1):
532
try:
533
with yt_dlp.YoutubeDL() as ydl:
534
ydl.download(urls)
535
return # Success
536
537
except (HTTPError, RequestError, ExtractorError) as e:
538
if attempt < max_retries:
539
print(f"Attempt {attempt + 1} failed: {e}")
540
print(f"Retrying in 5 seconds...")
541
import time
542
time.sleep(5)
543
else:
544
raise CustomDownloadError(f"Failed after {max_retries + 1} attempts: {e}")
545
546
except YoutubeDLError as e:
547
# Don't retry for other yt-dlp errors
548
raise CustomDownloadError(f"Download error: {e}")
549
550
# Usage
551
try:
552
download_with_retry(['https://www.youtube.com/watch?v=example'])
553
except CustomDownloadError as e:
554
print(f"Custom error: {e}")
555
```
556
557
## Error Recovery Strategies
558
559
### Automatic Retry with Backoff
560
561
```python
562
import yt_dlp
563
import time
564
from yt_dlp.networking.exceptions import HTTPError, RequestError
565
566
def exponential_backoff_download(urls, max_retries=5):
567
"""Download with exponential backoff retry strategy."""
568
569
for attempt in range(max_retries):
570
try:
571
with yt_dlp.YoutubeDL() as ydl:
572
ydl.download(urls)
573
return True
574
575
except (HTTPError, RequestError) as e:
576
if attempt < max_retries - 1:
577
wait_time = 2 ** attempt # Exponential backoff
578
print(f"Attempt {attempt + 1} failed, waiting {wait_time}s: {e}")
579
time.sleep(wait_time)
580
else:
581
print(f"All {max_retries} attempts failed")
582
return False
583
584
return False
585
```
586
587
## Types
588
589
```python { .api }
590
# Base exception type for all yt-dlp errors
591
YoutubeDLError = type[Exception]
592
593
# Specific exception types
594
ExtractorError = type[YoutubeDLError]
595
DownloadError = type[YoutubeDLError]
596
PostProcessingError = type[YoutubeDLError]
597
UnsupportedError = type[YoutubeDLError]
598
GeoRestrictedError = type[UnsupportedError]
599
600
# Network exception types
601
HTTPError = type[YoutubeDLError]
602
RequestError = type[YoutubeDLError]
603
SSLError = type[RequestError]
604
605
# Specialized exception types
606
ContentTooShortError = type[YoutubeDLError]
607
SameFileError = type[YoutubeDLError]
608
CookieLoadError = type[YoutubeDLError]
609
```