首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Faraday::ConnectionFailed的意外行为

Faraday::ConnectionFailed的意外行为
EN

Stack Overflow用户
提问于 2019-12-04 20:38:13
回答 1查看 395关注 0票数 1

我正在为一个从Faraday::ConnectionFailedFaraday::TimeoutError中解救出来的应用编程接口编写一个客户端,以重试相同的方法MAX_RETRIES次。

这是主要的方法:

代码语言:javascript
复制
def benchmark_request(path)
  retries ||= 0
  request_start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  response = yield

  total_request_seconds = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - request_start_time)
  Rails.logger.info "client request took (#{total_request_seconds}s): #{ENV['API_PATH_PREFIX']}#{path}"

  response
rescue Faraday::ConnectionFailed, Faraday::TimeoutError => e
  retries += 1
  retry if retries <= MAX_RETRIES
end

调用它的方法是:

代码语言:javascript
复制
 def get(path, params = {})
   benchmark_request(path) { token.get("#{ENV['API_PATH_PREFIX']}#{path}", params) }
 end

token.get来自使用Faradayoauth2 gem

有趣的地方在这里。我写了2个规范,每个我想要处理的异常都有一个。

代码语言:javascript
复制
context 'when the endpoint raises a ConnectionFailed' do
  let(:token_expires_at) { 1.hour.from_now.to_i }
  let(:response_body) { '' }
  let(:response_status) { 200 }

  before do
    allow(token).to receive(:get).and_raise(Faraday::ConnectionFailed)
    described_class.get(api_endpoint)
  end

  it 'is called MAX_RETRIES times' do
    expect(token).to have_received(:get).exactly(3).times
  end
end

context 'when the endpoint raises a TimeoutError' do
  let(:token_expires_at) { 1.hour.from_now.to_i }
  let(:response_body) { '' }
  let(:response_status) { 200 }

  before do
    allow(token).to receive(:get).and_raise(Faraday::TimeoutError)
    described_class.get(api_endpoint)
  end

  it 'is called MAX_RETRIES times' do
    expect(token).to have_received(:get).exactly(3).times
  end
end

测试测试ConnectionFailed失败,测试测试TimeoutError为绿色。引发的异常是:

代码语言:javascript
复制
1) Client::Base.get when the endpoint raises a ConnectionFailed is called MAX_RETRIES times
 Failure/Error: token.get(path, params)

 ArgumentError:
   wrong number of arguments (given 0, expected 1..2)
 # /home/ngw/.rvm/gems/ruby-2.6.2/gems/faraday-0.15.4/lib/faraday/error.rb:7:in `initialize'
 # ./app/lib/client/base.rb:13:in `get'
 # ./spec/lib/client/base_spec.rb:111:in `block (4 levels) in <top (required)>'

这显然是关于异常是如何初始化的。

有谁知道吗?

EN

回答 1

Stack Overflow用户

发布于 2020-07-01 01:00:27

代码语言:javascript
复制
before do
   allow(token).to receive(:get).and_raise(Faraday::TimeoutError, 'execution expired')
  described_class.get(api_endpoint)
end

我通过向and_raise方法传递一个second argument来解决这个问题。我认为这是因为Faraday有稍微不同的异常类。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59176256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档