rubywhen/how要用rescue/ensure?
ruby when/how to use rescue/ensure?
我有一个 class 来调用地理位置 api。下面的示例 url 和 Json 类似这样的响应
{ "location": { "lat": 31.0, "lng": 14.0 }, "accuracy": 112.4 }
我想捕获任何错误,例如 503、404 或任何其他可能由请求对象中的错误引起的错误。 ruby 中救援的正确方法是什么?还。如果有任何错误,我可以 return 来自 ensure 块的消息吗?
def findlocation
begin
location = httparty.get("https://www.googleapis.com/geolocation/v1/geolocate?key=#{API_KEY}")
rescue
# do something after catching error
ensure
return { "message" : "unable to find location" }
end
end
有几种方法可以处理这个问题。首先,我想假设您正在使用 HTTParty 库。如果是这种情况,那么您应该将其称为 HTTParty 而不是 httparty。
假设你想减少你能做的每一个错误
response = HTTParty.get("https://www.googleapis.com/geolocation/v1/geolocate?key=#{API_KEY}")
case response.code
when 503
# do something, Internal Server error
when 404
# do something, Page Not found
when 500...600
# do something, unexpected error
end
然而,上述情况假设您能够以某种方式与所请求的 url 交谈。如果在任何情况下你都无法与服务器对话并且你想从一般的 HTTParty 错误中解救出来,你可以做
def findlocation
begin
response = HTTParty.get("https://www.googleapis.com/geolocation/v1/geolocate?key=#{API_KEY}")
rescue HTTParty::Error => e
# Something is wrong
puts "#{e.message}"
end
ensure
允许您 运行 一段代码是否发生异常。因此,如果您希望执行一段代码,而不管您是否能够与 Google API 对话,请将其放入确保块
一般情况下,异常应该用于异常事件。不是常规的申请流程。
捕获异常时始终是特定的,并且只拯救您知道如何处理的异常。
begin
pats "hello world"
rescue
nil
end
此示例显示您问题中的代码存在严重缺陷 - 您创建了一个吞噬 NoMethodError 的黑洞,它会告诉我们代码中存在拼写错误。这使得调试非常困难。这种反模式被称为 Pokémon 异常处理(必须抓住他们)。
ensure
只是确保代码是 运行 无论代码是否引发异常。例如,它用于保证该方法关闭它已打开的文件处理程序或回滚事务。它是一个非常大的锤子,应该非常谨慎地使用。
当响应代码是 "error" 代码时,HTTPParty 实际上不会引发异常 - 因为它不是异常事件。它是处理 HTTP 请求时正常应用程序流程的一部分。狗屎发生了。如果您根本无法访问服务器或者甚至无法访问网络,HTTParty 会引发异常。这些都是特殊事件。
class GeolocationClient
include HTTParty
base_uri "https://www.googleapis.com/geolocation/v1"
format :json
attr_accessor :options
def initialize(api_key:)
@options = {
api_key: api_key
}
end
def geolocate
begin
response = self.class.get("/geolocate", options)
if response.successful?
response
else
logger.info("Geolocation API call was unsuccessful. Status code: #{response.code}")
handle_unsuccessful_request
end
rescue HTTParty::Error => e
logger.warn(e.message)
handle_unsuccessful_request
end
end
private
def handle_unsuccessful_request
{ "message" : "unable to find location" }
end
end
response.successful?
测试响应是否在 2xx
"happy range" 中。如果您想单独处理每个代码或代码范围,请使用 switch 语句。
我有一个 class 来调用地理位置 api。下面的示例 url 和 Json 类似这样的响应
{ "location": { "lat": 31.0, "lng": 14.0 }, "accuracy": 112.4 }
我想捕获任何错误,例如 503、404 或任何其他可能由请求对象中的错误引起的错误。 ruby 中救援的正确方法是什么?还。如果有任何错误,我可以 return 来自 ensure 块的消息吗?
def findlocation
begin
location = httparty.get("https://www.googleapis.com/geolocation/v1/geolocate?key=#{API_KEY}")
rescue
# do something after catching error
ensure
return { "message" : "unable to find location" }
end
end
有几种方法可以处理这个问题。首先,我想假设您正在使用 HTTParty 库。如果是这种情况,那么您应该将其称为 HTTParty 而不是 httparty。
假设你想减少你能做的每一个错误
response = HTTParty.get("https://www.googleapis.com/geolocation/v1/geolocate?key=#{API_KEY}")
case response.code
when 503
# do something, Internal Server error
when 404
# do something, Page Not found
when 500...600
# do something, unexpected error
end
然而,上述情况假设您能够以某种方式与所请求的 url 交谈。如果在任何情况下你都无法与服务器对话并且你想从一般的 HTTParty 错误中解救出来,你可以做
def findlocation
begin
response = HTTParty.get("https://www.googleapis.com/geolocation/v1/geolocate?key=#{API_KEY}")
rescue HTTParty::Error => e
# Something is wrong
puts "#{e.message}"
end
ensure
允许您 运行 一段代码是否发生异常。因此,如果您希望执行一段代码,而不管您是否能够与 Google API 对话,请将其放入确保块
一般情况下,异常应该用于异常事件。不是常规的申请流程。
捕获异常时始终是特定的,并且只拯救您知道如何处理的异常。
begin
pats "hello world"
rescue
nil
end
此示例显示您问题中的代码存在严重缺陷 - 您创建了一个吞噬 NoMethodError 的黑洞,它会告诉我们代码中存在拼写错误。这使得调试非常困难。这种反模式被称为 Pokémon 异常处理(必须抓住他们)。
ensure
只是确保代码是 运行 无论代码是否引发异常。例如,它用于保证该方法关闭它已打开的文件处理程序或回滚事务。它是一个非常大的锤子,应该非常谨慎地使用。
HTTPParty 实际上不会引发异常 - 因为它不是异常事件。它是处理 HTTP 请求时正常应用程序流程的一部分。狗屎发生了。如果您根本无法访问服务器或者甚至无法访问网络,HTTParty 会引发异常。这些都是特殊事件。
class GeolocationClient
include HTTParty
base_uri "https://www.googleapis.com/geolocation/v1"
format :json
attr_accessor :options
def initialize(api_key:)
@options = {
api_key: api_key
}
end
def geolocate
begin
response = self.class.get("/geolocate", options)
if response.successful?
response
else
logger.info("Geolocation API call was unsuccessful. Status code: #{response.code}")
handle_unsuccessful_request
end
rescue HTTParty::Error => e
logger.warn(e.message)
handle_unsuccessful_request
end
end
private
def handle_unsuccessful_request
{ "message" : "unable to find location" }
end
end
response.successful?
测试响应是否在 2xx
"happy range" 中。如果您想单独处理每个代码或代码范围,请使用 switch 语句。