0
# Error Handling
1
2
Comprehensive exception hierarchy for handling all error scenarios in YouTube transcript retrieval. Provides detailed error messages and actionable guidance for common issues.
3
4
## Capabilities
5
6
### Base Exception Classes
7
8
Root exception classes providing the foundation for all library-specific errors.
9
10
```python { .api }
11
class YouTubeTranscriptApiException(Exception):
12
"""
13
Base exception for all library errors.
14
15
All exceptions raised by this library inherit from this class.
16
"""
17
18
class CouldNotRetrieveTranscript(YouTubeTranscriptApiException):
19
"""
20
Base class for transcript retrieval failures.
21
22
Attributes:
23
video_id (str): YouTube video ID that failed
24
cause (str): Detailed error description
25
"""
26
27
def __init__(self, video_id):
28
"""
29
Initialize transcript retrieval error.
30
31
Args:
32
video_id (str): Video ID that failed
33
"""
34
35
@property
36
def video_id(self):
37
"""str: Video ID that failed"""
38
39
@property
40
def cause(self):
41
"""str: Detailed error cause description"""
42
```
43
44
### Video Availability Errors
45
46
Errors related to video accessibility and availability.
47
48
```python { .api }
49
class VideoUnavailable(CouldNotRetrieveTranscript):
50
"""
51
Video is no longer available on YouTube.
52
53
Common causes:
54
- Video deleted by uploader
55
- Video removed for policy violations
56
- Video made private
57
"""
58
59
class VideoUnplayable(CouldNotRetrieveTranscript):
60
"""
61
Video cannot be played due to restrictions.
62
63
Attributes:
64
reason (str): Primary reason for unplayability
65
sub_reasons (List[str]): Additional details
66
"""
67
68
def __init__(self, video_id, reason, sub_reasons):
69
"""
70
Initialize video unplayable error.
71
72
Args:
73
video_id (str): Video ID
74
reason (str): Primary reason
75
sub_reasons (List[str]): Additional details
76
"""
77
78
class InvalidVideoId(CouldNotRetrieveTranscript):
79
"""
80
Invalid video ID format provided.
81
82
Common causes:
83
- Passing full YouTube URL instead of video ID
84
- Malformed video ID
85
"""
86
87
class AgeRestricted(CouldNotRetrieveTranscript):
88
"""
89
Video is age-restricted and requires authentication.
90
91
Note:
92
Cookie authentication is currently disabled in the library.
93
"""
94
```
95
96
### Transcript Availability Errors
97
98
Errors related to transcript and subtitle availability.
99
100
```python { .api }
101
class TranscriptsDisabled(CouldNotRetrieveTranscript):
102
"""
103
Subtitles/transcripts are disabled for this video.
104
105
Common causes:
106
- Uploader disabled closed captions
107
- Video doesn't have transcripts
108
- Channel settings prevent transcript access
109
"""
110
111
class NoTranscriptFound(CouldNotRetrieveTranscript):
112
"""
113
No transcript found for requested languages.
114
115
Attributes:
116
_requested_language_codes (Iterable[str]): Languages that were requested
117
_transcript_data (TranscriptList): Available transcripts for debugging
118
"""
119
120
def __init__(self, video_id, requested_language_codes, transcript_data):
121
"""
122
Initialize no transcript found error.
123
124
Args:
125
video_id (str): Video ID
126
requested_language_codes (Iterable[str]): Requested languages
127
transcript_data (TranscriptList): Available transcripts
128
"""
129
```
130
131
### Translation Errors
132
133
Errors related to transcript translation functionality.
134
135
```python { .api }
136
class NotTranslatable(CouldNotRetrieveTranscript):
137
"""
138
Transcript cannot be translated.
139
140
Common causes:
141
- Transcript doesn't support translation
142
- Original transcript is already translated
143
"""
144
145
class TranslationLanguageNotAvailable(CouldNotRetrieveTranscript):
146
"""
147
Requested translation language is not available.
148
149
Common causes:
150
- Language code not supported by YouTube
151
- Translation not available for this transcript
152
"""
153
```
154
155
### Network and Blocking Errors
156
157
Errors related to network requests and IP blocking by YouTube.
158
159
```python { .api }
160
class YouTubeRequestFailed(CouldNotRetrieveTranscript):
161
"""
162
HTTP request to YouTube failed.
163
164
Attributes:
165
reason (str): HTTP error details
166
"""
167
168
def __init__(self, video_id, http_error):
169
"""
170
Initialize YouTube request failure.
171
172
Args:
173
video_id (str): Video ID
174
http_error (HTTPError): Original HTTP error
175
"""
176
177
class RequestBlocked(CouldNotRetrieveTranscript):
178
"""
179
Requests blocked by YouTube (generic blocking).
180
181
Common causes:
182
- Too many requests from IP
183
- Cloud provider IP blocked
184
- Bot detection triggered
185
186
Supports proxy-specific error messages via with_proxy_config().
187
"""
188
189
def __init__(self, video_id):
190
"""
191
Initialize request blocked error.
192
193
Args:
194
video_id (str): Video ID
195
"""
196
197
def with_proxy_config(self, proxy_config):
198
"""
199
Add proxy configuration context for better error messages.
200
201
Args:
202
proxy_config (ProxyConfig): Proxy configuration used
203
204
Returns:
205
RequestBlocked: Self for method chaining
206
"""
207
208
class IpBlocked(RequestBlocked):
209
"""
210
IP address specifically blocked by YouTube.
211
212
More severe than RequestBlocked, indicates IP-level ban.
213
"""
214
```
215
216
### Authentication and Access Errors
217
218
Errors related to authentication and special access requirements.
219
220
```python { .api }
221
class FailedToCreateConsentCookie(CouldNotRetrieveTranscript):
222
"""
223
Failed to automatically create consent cookie for GDPR compliance.
224
225
Common in EU regions where consent is required.
226
"""
227
228
class PoTokenRequired(CouldNotRetrieveTranscript):
229
"""
230
PO Token required for video access.
231
232
Rare error for videos requiring special authentication tokens.
233
"""
234
235
class YouTubeDataUnparsable(CouldNotRetrieveTranscript):
236
"""
237
YouTube response data cannot be parsed.
238
239
Usually indicates changes in YouTube's internal API.
240
"""
241
```
242
243
### Cookie-Related Errors
244
245
Errors related to cookie authentication (currently disabled).
246
247
```python { .api }
248
class CookieError(YouTubeTranscriptApiException):
249
"""
250
Base class for cookie-related errors.
251
252
Note:
253
Cookie authentication is temporarily disabled.
254
"""
255
256
class CookiePathInvalid(CookieError):
257
"""
258
Invalid cookie file path provided.
259
260
Args:
261
cookie_path (Path): Invalid path that was provided
262
"""
263
264
def __init__(self, cookie_path):
265
"""
266
Initialize invalid cookie path error.
267
268
Args:
269
cookie_path (Path): Invalid cookie file path
270
"""
271
272
class CookieInvalid(CookieError):
273
"""
274
Cookie file is invalid or expired.
275
276
Args:
277
cookie_path (Path): Path to invalid cookie file
278
"""
279
280
def __init__(self, cookie_path):
281
"""
282
Initialize invalid cookie error.
283
284
Args:
285
cookie_path (Path): Cookie file path
286
"""
287
```
288
289
## Usage Examples
290
291
### Basic Error Handling
292
293
```python
294
from youtube_transcript_api import YouTubeTranscriptApi
295
from youtube_transcript_api import (
296
VideoUnavailable,
297
TranscriptsDisabled,
298
NoTranscriptFound,
299
RequestBlocked,
300
InvalidVideoId
301
)
302
303
api = YouTubeTranscriptApi()
304
305
try:
306
transcript = api.fetch('dQw4w9WgXcQ')
307
print("Transcript retrieved successfully")
308
except VideoUnavailable:
309
print("Video is no longer available")
310
except TranscriptsDisabled:
311
print("Transcripts are disabled for this video")
312
except NoTranscriptFound:
313
print("No transcript found for requested languages")
314
except RequestBlocked as e:
315
print(f"Request blocked: {e}")
316
print("Consider using proxies or waiting before retrying")
317
except InvalidVideoId:
318
print("Invalid video ID - use video ID, not full URL")
319
except Exception as e:
320
print(f"Unexpected error: {e}")
321
```
322
323
### Detailed Error Information
324
325
```python
326
from youtube_transcript_api import YouTubeTranscriptApi
327
from youtube_transcript_api import (
328
NoTranscriptFound,
329
VideoUnplayable,
330
YouTubeRequestFailed
331
)
332
333
api = YouTubeTranscriptApi()
334
335
try:
336
transcript = api.fetch('invalid_video_id', languages=['es', 'en'])
337
except NoTranscriptFound as e:
338
print(f"Video ID: {e.video_id}")
339
print(f"Requested languages: {e._requested_language_codes}")
340
print(f"Available transcripts:\n{e._transcript_data}")
341
except VideoUnplayable as e:
342
print(f"Video unplayable: {e.reason}")
343
if e.sub_reasons:
344
print("Additional details:")
345
for reason in e.sub_reasons:
346
print(f" - {reason}")
347
except YouTubeRequestFailed as e:
348
print(f"HTTP request failed: {e.reason}")
349
```
350
351
### Proxy-Aware Error Handling
352
353
```python
354
from youtube_transcript_api import YouTubeTranscriptApi
355
from youtube_transcript_api.proxies import WebshareProxyConfig
356
from youtube_transcript_api import RequestBlocked, IpBlocked
357
358
proxy_config = WebshareProxyConfig('username', 'password')
359
api = YouTubeTranscriptApi(proxy_config=proxy_config)
360
361
try:
362
transcript = api.fetch('dQw4w9WgXcQ')
363
except RequestBlocked as e:
364
# Error message will include Webshare-specific guidance
365
print(f"Blocked despite Webshare proxy: {e}")
366
except IpBlocked as e:
367
print(f"IP blocked: {e}")
368
```
369
370
### Retry Logic with Error Handling
371
372
```python
373
from youtube_transcript_api import YouTubeTranscriptApi
374
from youtube_transcript_api import RequestBlocked, IpBlocked
375
import time
376
import random
377
378
def fetch_with_retry(video_id, max_retries=3):
379
api = YouTubeTranscriptApi()
380
381
for attempt in range(max_retries):
382
try:
383
return api.fetch(video_id)
384
except (RequestBlocked, IpBlocked) as e:
385
if attempt == max_retries - 1:
386
raise e
387
388
# Exponential backoff with jitter
389
delay = (2 ** attempt) + random.uniform(0, 1)
390
print(f"Request blocked, retrying in {delay:.1f}s...")
391
time.sleep(delay)
392
except Exception as e:
393
# Don't retry for other errors
394
raise e
395
396
# Usage
397
try:
398
transcript = fetch_with_retry('dQw4w9WgXcQ')
399
print("Successfully retrieved transcript")
400
except Exception as e:
401
print(f"Failed after retries: {e}")
402
```
403
404
### Language Fallback with Error Recovery
405
406
```python
407
from youtube_transcript_api import YouTubeTranscriptApi
408
from youtube_transcript_api import NoTranscriptFound
409
410
def fetch_best_transcript(video_id, preferred_languages=['en', 'es', 'fr']):
411
api = YouTubeTranscriptApi()
412
413
try:
414
# Try preferred languages first
415
transcript_list = api.list(video_id)
416
transcript = transcript_list.find_transcript(preferred_languages)
417
return transcript.fetch()
418
except NoTranscriptFound:
419
# Fall back to any available transcript
420
try:
421
# Get first available transcript
422
for transcript in transcript_list:
423
return transcript.fetch()
424
except Exception:
425
# Try generated transcripts only
426
try:
427
transcript = transcript_list.find_generated_transcript(['en'])
428
return transcript.fetch()
429
except NoTranscriptFound:
430
raise Exception("No transcripts available for this video")
431
432
# Usage
433
try:
434
transcript = fetch_best_transcript('dQw4w9WgXcQ')
435
print(f"Retrieved transcript in {transcript.language}")
436
except Exception as e:
437
print(f"Could not retrieve any transcript: {e}")
438
```
439
440
## Types
441
442
```python { .api }
443
from typing import List, Iterable, Optional
444
from pathlib import Path
445
from requests import HTTPError
446
447
# Exception hierarchy types
448
TranscriptRetrievalError = CouldNotRetrieveTranscript
449
NetworkError = Union[RequestBlocked, IpBlocked, YouTubeRequestFailed]
450
VideoError = Union[VideoUnavailable, VideoUnplayable, InvalidVideoId]
451
TranscriptError = Union[TranscriptsDisabled, NoTranscriptFound]
452
TranslationError = Union[NotTranslatable, TranslationLanguageNotAvailable]
453
```