【问题标题】:How can I evaluate if a rescue case was reached?我如何评估是否达到了救援案例?
【发布时间】:2019-06-11 21:43:32
【问题描述】:

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

我对 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

【问题讨论】:

  • 顺便说一句,Hash['message' => 'There was...'] 不是创建哈希的正确方法。 Hash[] method 返回一个新的哈希,其中对象的键和值作为其参数。你给出的参数已经是一个哈希(键'message' 和值'There was...'),你得到的是它的副本。您应该只使用哈希文字:{ 'message' => 'There was...' }.

标签: ruby httparty


【解决方案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,那么您假设任何错误都将在您的代码中以单一方式处理。

【讨论】:

    【解决方案2】:

    按照HttParty gem 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
    

    【讨论】:

      猜你喜欢
      • 2013-09-06
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多