要捕捉YouTube API中的"视频已在播放列表中"错误,可以使用try-except语句来处理异常。以下是一个使用Python的代码示例:
from googleapiclient.errors import HttpError
def add_video_to_playlist(youtube, video_id, playlist_id):
try:
request = youtube.playlistItems().insert(
part="snippet",
body={
"snippet": {
"playlistId": playlist_id,
"resourceId": {
"kind": "youtube#video",
"videoId": video_id
}
}
}
)
response = request.execute()
print("视频添加到播放列表成功!")
except HttpError as e:
if e.resp.status == 400:
error = e._get_reason().split('\n')[0]
if error == 'Video already in playlist':
print("视频已在播放列表中!")
else:
print("发生了其他错误:", error)
else:
print("发生了其他HTTP错误:", e.resp.status, e._get_reason())
# 使用示例
video_id = "YOUR_VIDEO_ID"
playlist_id = "YOUR_PLAYLIST_ID"
add_video_to_playlist(youtube, video_id, playlist_id)
在上面的代码中,我们定义了一个add_video_to_playlist
函数来添加视频到播放列表。在try块中,我们发送一个插入请求来将视频添加到指定的播放列表。如果API返回400错误,我们通过检查错误消息来判断视频是否已经在播放列表中。如果是这样,我们打印出相应的消息。如果出现其他HTTP错误,我们也打印出相应的消息。