0

I use this code to get info of an youtube video(youtube_itgem)

  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

The problem is that sometimes, the original youtube video is deleted, like this: https://www.youtube.com/watch?v=lsZFkiimpKI. So video_info = Video.yt_session.video_by(self.source_id) will reports OpenURI::HTTPError: 404, and the code cannot continue to get info of next videos.

I want to delete this non-exist video its source is not available anymore, how can I do that? Maybe by rescue?

I tried if Video.yt_session.video_by(self.source_id), but it doesn't work.

ZK Zhao
  • 19,885
  • 47
  • 132
  • 206

1 Answers1

1

Did you try the following:

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

Example with multiple cases of catching errors:

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
Christos Hrousis
  • 707
  • 4
  • 16
  • Can I make it to rescue other errors as well? Sometimes it's other errors, and I want to delete the entry too. – ZK Zhao Feb 10 '15 at 13:56
  • Yes, but please make sure that you remember that it is bad ruby style to rescue Exception => e, and try to make what you rescue specific. You can read more about this idealogy [here.](http://stackoverflow.com/questions/10048173/why-is-it-bad-style-to-rescue-exception-e-in-ruby) I will update my answer to reflect your comment. – Christos Hrousis Feb 11 '15 at 02:31