How to save Socket error in Ruby with RestClient?

I am using RestClient to create a network call in the ruby ​​class. I get a SocketError when I am not connected to the Internet. I added a rescue block to catch the exception, but I can't do it.

error message: SocketError (Failed to open TCP connection to api.something.com:443 (getaddrinfo: Name or service not known))

 module MyProject class Client def get_object(url, params={}) response = RestClient.get(url, {params: params}) rescue SocketError => e puts "In Socket errror" rescue => e puts (e.class.inspect) end end end 

Wide rescue is called and SocketError is SocketError , but why the previous rescue SocketError does not start!

Do you see what I am missing?

+7
ruby ruby-on-rails sockets
source share
1 answer

There are a few exceptions that you will need to save if you want to gracefully fail.

 require 'rest-client' def get_object(url, params={}) response = RestClient.get(url, {params: params}) rescue RestClient::ResourceNotFound => e p e.class rescue SocketError => e p e.class rescue Errno::ECONNREFUSED => e p e.class end get_object('https://www.google.com/missing') get_object('https://dasdkajsdlaadsasd.com') get_object('dasdkajsdlaadsasd.com') get_object('invalid') get_object('127.0.0.1') 

Since you may have problems with uri 404 or be a domain that does not exist, IP, etc.

As you can see above, you may have different scenarios that may occur when connecting to a remote uri. The code above rescues from the most common scenarios.

The first URL is missing, which is handled by RestClient itself.

Below are three invalid domains that fail in SocketError (basically, a DNS error in this case).

Finally, in the last call, we try to connect to an IP address that does not have a server, so it calls ERRNO :: ECONNREFUSED

+1
source share

All Articles