简体   繁体   English

如何使用RestClient拯救Ruby中的套接字错误?

[英]How to rescue Socket Error in Ruby with RestClient?

I am using RestClient to make a network call in the ruby class. 我正在使用RestClient在ruby类中进行网络调用。 I am getting a SocketError whenever I am not connected to the internet. 每当我没有连接到互联网时,我都会收到SocketError I have added a rescue block to catch the exception still I am not able to do so. 我已经添加了一个救援块以捕获异常,但我无法这样做。

the error message is: SocketError (Failed to open TCP connection to api.something.com:443 (getaddrinfo: Name or service not known)) 错误消息是: 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

The broad rescue gets called and print SocketError , but why the previous rescue SocketError is not triggered! 广泛的救援被调用并打印SocketError ,但为什么以前的rescue SocketError没有被触发!

Do you see something that I am missing? 你看到我遗失的东西吗?

There are a couple of exceptions you'll need to rescue in case you want to fail gracefully. 如果你想要优雅地失败,你需要拯救一些例外。

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')

Because you can have problems regarding the uri being a 404 destination, or be a domain that doesn't existing, an IP, and so on. 因为您可能有关于uri是404目的地的问题,或者是不存在的域,IP等等。

As you can see above, you can have different scenarios that you may encounter when dealing with connecting to a remote uri. 如您所见,您可以在处理连接到远程uri时遇到不同的场景。 The code above rescue from the most common scenarios. 上面的代码从最常见的场景中解救出来。

The first one the URL is missing, which is handled by RestClient itself. 第一个缺少URL,由RestClient本身处理。

The the following three below are invalid domains, which will fail with SocketError (basically a DNS error in this case). 以下三个是无效域,它们将因SocketError而失败(在这种情况下基本上是DNS错误)。

Finally in the last call we try to connect to an IP that has no server running on it - therefore it throws an ERRNO::ECONNREFUSED 最后在最后一次调用中我们尝试连接到没有运行服务器的IP - 因此它会抛出一个ERRNO :: ECONNREFUSED

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM