我如何评估是否已到达救援案例?

时间:2019-06-11 21:43:32

标签: ruby httparty

我正在运行异常处理程序,然后在另一个文件中评估异常处理程序是否已成功运行,或者是否运行了救援案例。

我对Ruby还是很陌生,我不确定如何评估异常处理程序中实际发生的情况以及如何存储结果(或者甚至可以)。代码是这样的。

文件一-运行API调用

begin
  HTTParty.get(BASE_URL + url)
rescue
  Hash['message' => 'There was an error connecting with the API, contact support if error persists.']
end

文件二-分析API调用是否成功

response = call_to_api #api call is ran in file one

if response == #I'm not sure what to put here, but it needs to check if the exception handler didn't trip the rescue
  success
else
  error
end

2 个答案:

答案 0 :(得分:1)

您可以使用不同的方法来处理,请看下面两个示例:

# You can catch the error just to handle it and bypass to the caller
# In this case, the caller will need to rescue your custom error
# Example 1
def my_method
  begin
    ...
  rescue
    raise MyCustomError
  end
end

begin
  my_method
rescue MyCustomError => err
  ...
end

# You can provide the error through a block
# Example 2
def my_method
  begin
    yield MyApi.call
  rescue
    yield :fail, { message: 'error' }
  end
end

my_method do |result, error|
  ...
end

考虑不要处理紧急情况中的一般错误,而是实际上捕获特定的错误并加以处理,如果您只放置rescue,则假定所有错误都将以单一方式处理。

答案 1 :(得分:0)

HttParty宝石here之后,您可以

# Use the class methods to get down to business quickly
response = HTTParty.get('http://api.stackexchange.com/2.2/questions?site=stackoverflow')

puts response.body, response.code, response.message, response.headers.inspect

因此,在您的调用api函数中,这取决于API返回的内容

response = call_to_api #api call is ran in file one

if response.code == 200 or response.message == "OK"
  success
else
  error
end
相关问题