What are best practices for handling errors and exceptions when making HTTP requests in PHP, especially when dealing with external APIs like YouTube?

When making HTTP requests in PHP, especially when dealing with external APIs like YouTube, it is important to handle errors and exceptions properly to ensure robustness and reliability of your application. One common approach is to use try-catch blocks to catch exceptions thrown during the request process and handle them accordingly, such as logging the error or displaying a user-friendly message.

try {
    $response = file_get_contents('https://www.googleapis.com/youtube/v3/videos?id=VIDEO_ID&key=YOUR_API_KEY&part=snippet');
    
    if ($response === false) {
        throw new Exception('Failed to fetch data from YouTube API');
    }
    
    // Process the response data
} catch (Exception $e) {
    // Log the error or display a user-friendly message
    echo 'Error: ' . $e->getMessage();
}