Search code examples
rubyexceptionrest-client

ruby rest_client exception handling


I'd like to do some HTTP REST requests in Ruby, using rest-client gem,

Following readme.md at https://github.com/rest-client/rest-client I wrote this simple command line script, trying to catch exceptions in case of response codes differents from 2xx:

RestClient.get('http://thisurldoesnotexist/resource') { |response, request, result, &block|
case response.code
  when 200
    p "It worked !"
    response
  else
    response.return!(request, result, &block)
  end
}

Hi got this on stdout output:

/home/*****/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http.rb:878:in `initialize': getaddrinfo: Name or service not known (SocketError)
    from /home/solyaris/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http.rb:878:in `open'
    from /home/solyaris/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http.rb:878:in `block in connect'
    from /home/solyaris/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/timeout.rb:52:in `timeout'
    from /home/solyaris/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http.rb:877:in `connect'
    from /home/solyaris/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http.rb:862:in `do_start'
    from /home/solyaris/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http.rb:851:in `start'
    from /home/solyaris/.rvm/gems/ruby-2.0.0-p247/gems/rest-client-1.6.7/lib/restclient/request.rb:172:in `transmit'
    from /home/solyaris/.rvm/gems/ruby-2.0.0-p247/gems/rest-client-1.6.7/lib/restclient/request.rb:64:in `execute'
    from /home/solyaris/.rvm/gems/ruby-2.0.0-p247/gems/rest-client-1.6.7/lib/restclient/request.rb:33:in `execute'
    from /home/solyaris/.rvm/gems/ruby-2.0.0-p247/gems/rest-client-1.6.7/lib/restclient.rb:68:in `get'
    from prova_rest.rb:3:in `<main>'

How can i catch SocketError ? where I'm wrong ?

thanks giorgio


Solution

  • The callback block is executed only when receiving some response from the server. In this case, the name resolving is failed so RestClient.get just throws an exception without entering the block. Thus just wrap your code within a begin...end construct.

    begin
      RestClient.get('http://thisurldoesnotexist/resource') { |response, request, result, &block|
      case response.code
        when 200
          p "It worked !"
          response
        else
          response.return!(request, result, &block)
        end
      }
    rescue SocketError => e
      # Handle your error here
    end