umezo
umezo

Reputation: 1579

How to add rescue to simple uri parsing method

I have a simple method that uploads an image from a URL.

def photo_from_url(url)
  if !Nokogiri::HTML(open(url)).css("meta[property='og:image']").blank?
    photo_url = Nokogiri::HTML(open(url)).css("meta[property='og:image']").first.attributes["content"]
    self.photo = URI.parse(photo_url)
    self.save
  end
end

This works fine in most cases, but sometimes returns can't convert URI::Generic into String if the url isn't formatted as expected. I just want to forgo saving the photo in such a case. What do I need to add to the method?

I tried adding

rescue => e                                                      
  error_message = e.message                                      
  response_message = "Unknown error"                             
end

to the end of the method based on this post, but this results in a SyntaxError:

unexpected keyword_rescue, expecting keyword_end

How/Where do I use the rescue method correctly? Currently, the method works often enough as is, so I'd be happy with it just skipping any unformatted urls, as opposed to returning an error. Thanks for helping out a newbie.

Upvotes: 0

Views: 1530

Answers (1)

Magnus Skog
Magnus Skog

Reputation: 146

Try this:

def photo_from_url(url)
  begin
    if !Nokogiri::HTML(open(url)).css("meta[property='og:image']").blank?
      photo_url = Nokogiri::HTML(open(url)).css("meta[property='og:image']").first.attributes["content"]
      self.photo = URI.parse(photo_url)
      self.save
    end
  rescue => e
    puts "error"
  end
end

Upvotes: 1

Related Questions