Faraday :: ConnectionFailed

时间:2019-12-04 12:38:12

标签: ruby api http faraday

我正在为API编写客户端,该API可从Faraday::ConnectionFailedFaraday::TimeoutError抢救以重试相同方法MAX_RETRIES次。

这是涉及的主要方法:

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

调用的方法是:

 def get(path, params = {})
   benchmark_request(path) { token.get("#{ENV['API_PATH_PREFIX']}#{path}", params) }
 end

token.get来自使用oauth2的{​​{1}}宝石

这是有趣的地方。 我写了2个规范,每个要处理的异常1个。

Faraday

测试测试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

显然与异常的初始化方式有关。

有人有什么主意吗?

1 个答案:

答案 0 :(得分:0)

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

我通过将second argument传递给and_raise方法解决了这个问题。我认为这是因为法拉第的异常类略有不同。