how to test open-uri url exist before processing any data how to test open-uri url exist before processing any data ruby ruby

how to test open-uri url exist before processing any data


You could try something along the lines of

    require 'open-uri'    smth.css.each do |item|     begin        open('item[:name]', 'wb') do |file|         file << open('item[:href]').read       end     rescue => e       case e       when OpenURI::HTTPError         # do something       when SocketError         # do something else       else         raise e       end      rescue SystemCallError => e       if e === Errno::ECONNRESET        # do something else       else        raise e       end     end   end

I don't know of any way of testing the connection without opening it and trying, so rescuing these errors would be the only way I can think of. The thing to be aware of is that OpenURI::HTTPError and SocketError are both subclasses of StandardError, whereas Errno::ECONNRESET is a subclass of SystemCallError. So rescue => e won't catch Errno::ECONNRESET.


I was able to solve this problem by using a conditional if/else statement to check the return value of the action for "failure":

def controller_action    url = "some_API"    response = open(url).read    data = JSON.parse(response)["data"]    if response["status"] == "failure"        redirect_to :action => "home"     else        do_something_else    endend