CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-yt-dlp

A feature-rich command-line audio/video downloader forked from youtube-dl

Overview
Eval results
Files

exceptions.mddocs/

Exception Handling

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.

Capabilities

Base Exception Classes

Core exception hierarchy providing foundation for all yt-dlp error conditions.

class YoutubeDLError(Exception):
    """
    Base exception class for all yt-dlp errors.
    
    Provides common functionality for error messages,
    context information, and error categorization.
    """
    
    def __init__(self, msg=None):
        """
        Initialize base yt-dlp exception.
        
        Parameters:
        - msg: str|None, error message
        """

class UnsupportedError(YoutubeDLError): 
    """
    Exception for unsupported operations or content.
    
    Raised when attempting operations not supported
    by the current context or configuration.
    """
    
class RegexNotFoundError(UnsupportedError):
    """
    Exception for regex pattern matching failures.
    
    Raised when required regex patterns don't match
    expected content during extraction.
    """
    
class GeoRestrictedError(UnsupportedError):
    """
    Exception for geographically restricted content.
    
    Indicates content is not available in the current
    geographic location due to regional restrictions.
    """
    
    def __init__(self, msg, countries=None, **kwargs):
        """
        Initialize geo-restriction exception.
        
        Parameters:
        - msg: str, error message
        - countries: list[str]|None, allowed countries
        - **kwargs: additional context information
        """

Extraction Errors

Exceptions related to information extraction and site-specific processing.

class ExtractorError(YoutubeDLError):
    """
    Exception for extractor operation failures.
    
    Raised when extractors encounter problems parsing
    content, accessing APIs, or processing responses.
    """
    
    def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None, ie=None):
        """
        Initialize extractor error.
        
        Parameters:
        - msg: str, error message
        - tb: str|None, traceback information
        - expected: bool, whether error was expected
        - cause: Exception|None, underlying cause
        - video_id: str|None, video identifier
        - ie: str|None, extractor name
        """

class UnsupportedURLIE(ExtractorError):
    """
    Exception for unsupported URL patterns.
    
    Raised when no extractor can handle the provided URL
    or when URL format is not recognized.
    """

class LoginRequiredError(ExtractorError):
    """
    Exception indicating authentication is required.
    
    Raised when content requires login credentials
    that were not provided or are invalid.
    """
    
class PrivateVideoError(ExtractorError):
    """
    Exception for private or restricted videos.
    
    Raised when attempting to access private content
    without proper authorization or permissions.
    """

class ContentTooShortError(YoutubeDLError):
    """
    Exception for incomplete downloads.
    
    Raised when downloaded content is shorter than
    expected based on Content-Length headers.
    """
    
    def __init__(self, downloaded, expected):
        """
        Initialize content length error.
        
        Parameters:
        - downloaded: int, bytes downloaded
        - expected: int, expected bytes
        """

Download Errors

Exceptions related to file downloading and network operations.

class DownloadError(YoutubeDLError):
    """
    Exception for download operation failures.
    
    Raised when file downloads fail due to network issues,
    server errors, or file system problems.
    """
    
    def __init__(self, msg, exc_info=None):
        """
        Initialize download error.
        
        Parameters:
        - msg: str, error message
        - exc_info: tuple|None, exception information
        """

class DownloadCancelled(YoutubeDLError):
    """
    Exception for user-cancelled downloads.
    
    Raised when downloads are interrupted by user
    action such as Ctrl+C or explicit cancellation.
    """

class MaxDownloadsReached(DownloadError):
    """
    Exception when maximum download limit is reached.
    
    Raised when the configured maximum number of
    downloads has been completed.
    """

class SameFileError(YoutubeDLError):
    """
    Exception for file conflict errors.
    
    Raised when attempting to write to a file that
    would conflict with existing files or operations.
    """
    
    def __init__(self, filename):
        """
        Initialize file conflict error.
        
        Parameters:
        - filename: str, conflicting filename
        """

class ExistingVideoReached(DownloadError):
    """
    Exception when encountering existing video in archive.
    
    Raised when break_on_existing is enabled and
    a video already exists in the download archive.
    """

class RejectedVideoReached(DownloadError):
    """
    Exception when video is rejected by filters.
    
    Raised when break_on_reject is enabled and
    a video is rejected by match filters.
    """

Post-Processing Errors

Exceptions related to post-processing operations and file transformations.

class PostProcessingError(YoutubeDLError):
    """
    Exception for post-processing failures.
    
    Raised when post-processors encounter errors during
    file processing, conversion, or transformation.
    """
    
    def __init__(self, msg):
        """
        Initialize post-processing error.
        
        Parameters:
        - msg: str, error message
        """

Network and Authentication Errors

Exceptions related to network connectivity, authentication, and cookie handling.

class CookieLoadError(YoutubeDLError):
    """
    Exception for cookie loading failures.
    
    Raised when cookies cannot be loaded from browsers,
    files, or other sources due to access or format issues.
    """

class HTTPError(YoutubeDLError):
    """
    Exception for HTTP response errors.
    
    Raised when HTTP requests receive error status codes
    or encounter network-related problems.
    """
    
    def __init__(self, status_code, response_data=None):
        """
        Initialize HTTP error.
        
        Parameters:
        - status_code: int, HTTP status code
        - response_data: str|None, response content
        """

class RequestError(YoutubeDLError):
    """
    Exception for request processing errors.
    
    Raised when HTTP requests fail due to network issues,
    timeouts, or connection problems.
    """

class SSLError(RequestError):
    """
    Exception for SSL/TLS connection errors.
    
    Raised when secure connections fail due to certificate
    issues or SSL/TLS protocol problems.
    """

class NoSupportingHandlers(RequestError):
    """
    Exception when no request handler is available.
    
    Raised when no network backend can handle the
    requested URL scheme or protocol.
    """

Playlist and Entry Errors

Exceptions related to playlist processing and entry management.

class EntryNotInPlaylist(YoutubeDLError):
    """
    Exception when playlist entry is not found.
    
    Raised when attempting to access playlist entries
    that don't exist or are out of range.
    """

class ReExtractInfo(YoutubeDLError):
    """
    Exception requesting information re-extraction.
    
    Special exception used internally to signal that
    information extraction should be retried.
    """

Utility and Processing Errors

Exceptions from utility functions and specialized processing operations.

class _UnsafeExtensionError(Exception):
    """
    Exception for unsafe file extensions.
    
    Raised when file extensions are deemed unsafe
    for security reasons unless explicitly allowed.
    """
    
    @staticmethod
    def sanitize_extension(ext, prepend=False):
        """
        Sanitize file extension for safety.
        
        Parameters:
        - ext: str, file extension
        - prepend: bool, prepend dot if missing
        
        Returns:
        str: sanitized extension
        
        Raises:
        _UnsafeExtensionError: if extension is unsafe
        """

Usage Examples

Basic Exception Handling

import yt_dlp
from yt_dlp.utils import DownloadError, ExtractorError

try:
    with yt_dlp.YoutubeDL() as ydl:
        ydl.download(['https://www.example.com/video'])
except DownloadError as e:
    print(f"Download failed: {e}")
except ExtractorError as e:
    print(f"Extraction failed: {e}")
except yt_dlp.utils.YoutubeDLError as e:
    print(f"General yt-dlp error: {e}")

Specific Error Handling

import yt_dlp
from yt_dlp.utils import (
    GeoRestrictedError, LoginRequiredError, 
    PrivateVideoError, UnsupportedURLIE
)

urls = ['https://www.youtube.com/watch?v=example']

try:
    with yt_dlp.YoutubeDL() as ydl:
        ydl.download(urls)
        
except GeoRestrictedError as e:
    print(f"Content geo-restricted: {e}")
    print(f"Available in countries: {e.countries}")
    
except LoginRequiredError as e:
    print(f"Login required: {e}")
    print("Please provide credentials using --username and --password")
    
except PrivateVideoError as e:
    print(f"Private video: {e}")
    
except UnsupportedURLIE as e:
    print(f"Unsupported URL: {e}")
    
except ExtractorError as e:
    print(f"Extractor error: {e}")
    if e.video_id:
        print(f"Video ID: {e.video_id}")
    if e.ie:
        print(f"Extractor: {e.ie}")

Network Error Handling

import yt_dlp
from yt_dlp.networking.exceptions import HTTPError, SSLError, RequestError

try:
    with yt_dlp.YoutubeDL() as ydl:
        ydl.download(['https://www.youtube.com/watch?v=example'])
        
except HTTPError as e:
    print(f"HTTP error {e.status_code}: {e}")
    
except SSLError as e:
    print(f"SSL/TLS error: {e}")
    print("Try using --no-check-certificate if the certificate is self-signed")
    
except RequestError as e:
    print(f"Network error: {e}")
    
except ConnectionError as e:
    print(f"Connection failed: {e}")

Post-Processing Error Handling

import yt_dlp
from yt_dlp.utils import PostProcessingError

ydl_opts = {
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
    }],
}

try:
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download(['https://www.youtube.com/watch?v=example'])
        
except PostProcessingError as e:
    print(f"Post-processing failed: {e}")
    print("Check that FFmpeg is installed and accessible")

Download Interruption Handling

import yt_dlp
from yt_dlp.utils import (
    DownloadCancelled, MaxDownloadsReached,
    ExistingVideoReached, RejectedVideoReached
)

ydl_opts = {
    'max_downloads': 5,
    'break_on_existing': True,
    'download_archive': 'archive.txt',
}

try:
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download(['https://www.youtube.com/playlist?list=example'])
        
except DownloadCancelled:
    print("Download cancelled by user")
    
except MaxDownloadsReached:
    print("Maximum download limit reached")
    
except ExistingVideoReached:
    print("Stopped at existing video (already in archive)")
    
except RejectedVideoReached:
    print("Stopped at rejected video (filtered out)")

Comprehensive Error Handler

import yt_dlp
import sys
from yt_dlp.utils import YoutubeDLError

def safe_download(urls, options=None):
    """
    Safely download URLs with comprehensive error handling.
    
    Parameters:
    - urls: list[str], URLs to download
    - options: dict|None, yt-dlp options
    
    Returns:
    bool: True if successful, False otherwise
    """
    if options is None:
        options = {}
    
    try:
        with yt_dlp.YoutubeDL(options) as ydl:
            ydl.download(urls)
        return True
        
    except KeyboardInterrupt:
        print("\nDownload interrupted by user")
        return False
        
    except YoutubeDLError as e:
        print(f"yt-dlp error: {e}")
        return False
        
    except Exception as e:
        print(f"Unexpected error: {e}")
        return False

# Usage
urls = ['https://www.youtube.com/watch?v=example']
success = safe_download(urls, {'format': 'best[height<=720]'})

if not success:
    sys.exit(1)

Custom Exception Handling

import yt_dlp
from yt_dlp.utils import YoutubeDLError

class CustomDownloadError(YoutubeDLError):
    """Custom exception for application-specific errors."""
    pass

def download_with_retry(urls, max_retries=3):
    """
    Download with retry logic and custom error handling.
    
    Parameters:
    - urls: list[str], URLs to download
    - max_retries: int, maximum retry attempts
    
    Raises:
    CustomDownloadError: if all retries fail
    """
    for attempt in range(max_retries + 1):
        try:
            with yt_dlp.YoutubeDL() as ydl:
                ydl.download(urls)
            return  # Success
            
        except (HTTPError, RequestError, ExtractorError) as e:
            if attempt < max_retries:
                print(f"Attempt {attempt + 1} failed: {e}")
                print(f"Retrying in 5 seconds...")
                import time
                time.sleep(5)
            else:
                raise CustomDownloadError(f"Failed after {max_retries + 1} attempts: {e}")
        
        except YoutubeDLError as e:
            # Don't retry for other yt-dlp errors
            raise CustomDownloadError(f"Download error: {e}")

# Usage
try:
    download_with_retry(['https://www.youtube.com/watch?v=example'])
except CustomDownloadError as e:
    print(f"Custom error: {e}")

Error Recovery Strategies

Automatic Retry with Backoff

import yt_dlp
import time
from yt_dlp.networking.exceptions import HTTPError, RequestError

def exponential_backoff_download(urls, max_retries=5):
    """Download with exponential backoff retry strategy."""
    
    for attempt in range(max_retries):
        try:
            with yt_dlp.YoutubeDL() as ydl:
                ydl.download(urls)
            return True
            
        except (HTTPError, RequestError) as e:
            if attempt < max_retries - 1:
                wait_time = 2 ** attempt  # Exponential backoff
                print(f"Attempt {attempt + 1} failed, waiting {wait_time}s: {e}")
                time.sleep(wait_time)
            else:
                print(f"All {max_retries} attempts failed")
                return False
    
    return False

Types

# Base exception type for all yt-dlp errors
YoutubeDLError = type[Exception]

# Specific exception types
ExtractorError = type[YoutubeDLError]
DownloadError = type[YoutubeDLError] 
PostProcessingError = type[YoutubeDLError]
UnsupportedError = type[YoutubeDLError]
GeoRestrictedError = type[UnsupportedError]

# Network exception types
HTTPError = type[YoutubeDLError]
RequestError = type[YoutubeDLError]
SSLError = type[RequestError]

# Specialized exception types
ContentTooShortError = type[YoutubeDLError]
SameFileError = type[YoutubeDLError]
CookieLoadError = type[YoutubeDLError]

Install with Tessl CLI

npx tessl i tessl/pypi-yt-dlp

docs

configuration.md

core-download.md

exceptions.md

extractor-system.md

index.md

post-processing.md

utilities.md

tile.json