Search code examples
ruby-on-railsrubyopen-uri

How to rescue 404s from OpenURI in a map


I am doing a map to format some data appropriately for a PDF export. A part of this is using OpenURI to open an image. However, the problem I've got is that some of the image links are to external sites and broken. Thus I randomly get 404 errors...

I've tried doing a rescue within the map, but it errors. I've tried doing a rescue within the method but then it results in no data. What is the correct way to do this?

Ideally I would like to set the image as a placeholder image I have on my server. Would it be better to define a separate method to handle this first?

Here is my method at the moment:

  def wish_list_item_rows
    WishListItem.where(:wish_list_id => @wish_list.id).map { |wishlistitem| [wishlistitem.product.name, {:image => open(wishlistitem.product.image_url)}] }
  end

Solution

  • You can rescue within a map block (you may be getting the syntax a bit off) but it'll generally be cleaner to move the rescue to its own method. Replace open with a call to a method like

    def safe_open(url)
      open(url)
    rescue # put a specific error class here ideally
      load_placeholder_image
    end
    

    Finished Code:

      def safe_open(url)
        if url.blank?
          safe_open = "#{Rails.root}/app/assets/images/placeholder.png"
        else
          open(url)
        end
      rescue OpenURI::HTTPError => e
        if e.message == '404 Not Found'
          safe_open = "#{Rails.root}/app/assets/images/placeholder.png"
        end
      end