我使用此代码获取youtube视频(youtube_it
gem)
video_info = Video.yt_session.video_by(self.source_id)
hits = video_info.view_count
if video_info.rating
self.rating = video_info.rating.average
self.likes = video_info.rating.likes.to_i
end
问题在于,有时原始YouTube视频会被删除,如下所示:https://www.youtube.com/watch?v=lsZFkiimpKI
。
因此video_info = Video.yt_session.video_by(self.source_id)
会报告OpenURI::HTTPError: 404
,代码无法继续获取下一个视频的信息。
我想删除这个不存在的视频,它的来源不再可用,我该怎么做?也许是rescue
?
我尝试了if Video.yt_session.video_by(self.source_id)
,但它不起作用。
答案 0 :(得分:1)
您是否尝试过以下操作:
begin
video_info = Video.yt_session.video_by(self.source_id)
hits = video_info.view_count
if video_info.rating
self.rating = video_info.rating.average
self.likes = video_info.rating.likes.to_i
end
rescue OpenURI::HTTPError
# Delete the entry
end
多个捕获错误案例:
begin
# Do the thing
rescue OpenURI::HTTPError
# Delete the entry
rescue OpenURI::DifferentErrorType
# Do something different
resuce OpenURI::AnotherType, OpenURI::ASpecialError
# Do something radically different
end