YouTube API error halts execution (googleapiclient.errors.HttpError)

  error-handling, python, youtube-api

I have a script that loops through some YouTube videos and adds them to a playlist:

for page in pages:
   add_video_to_playlist(youtube,upsert_id,my_playlist)

def add_video_to_playlist(youtube_obj,video_id,yt_pl_id):
    request = youtube_obj.playlistItems().insert(
        part="snippet",
        body={
          "snippet": {
            "playlistId": yt_pl_id,
            #"position": 0,
            "resourceId": {
              "kind": "youtube#video",
              "videoId": video_id
            }
          }
        }
    )
    try:
        response = request.execute()
        print(response['snippet']['title'])
    except HttpError as err:
        return "Error: " + str(err)

Periodically, I get a bad video ID and execution halts with a message like this:

googleapiclient.errors.HttpError: <HttpError 404 when requesting https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&alt=json returned "Video not found.". Details: "Video not found.">

How can I print the error message without exiting my loop, so that execution can continue to the next video in the loop?

Source: Python Questions

LEAVE A COMMENT