在我的项目中,我使用以下小型库与外部服务进行交互:
class ExternalServiceInteraction
include Singleton
URL = Rails.env.production? ? 'https://first.production.url.com' : 'http://sandbox.url.com'
API_KEY = Rails.env.production? ? 'qwerty' : 'qwerty'
DOMAIN = Rails.env.production? ? 'prod.net' : 'stage.net'
def connection
conn = Faraday.new(url: URL) do |faraday|
faraday.response :logger # log requests to STDOUT
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
end
end
def return_response(item=true)
if @resp.status == 200
response = item ? Hash.from_xml(@resp.body)['xml']['item'] : Hash.from_xml(@resp.body)['xml']
else
response = Hash.from_xml(@resp.body)['xml']['error']
Rails.logger.info "response_error=#{response}"
end
response
end
def get_subscribers
path = 'subscribers'
data = { 'X-API-KEY' => API_KEY, 'domain' => DOMAIN }
@resp = connection.get(path, data)
return_response
end
def get_subscriber(physical_id)
path = 'subscriber'
data = { 'X-API-KEY' => API_KEY, 'Physical_ID' => physical_id, 'domain' => DOMAIN }
@resp = connection.get(path, data)
return_response
end
# and so on
end
现在我想使用“https://second.production.url.com”,如果通过第一个 url 进行交互服务有任何错误,如何更好地设置它?
起初,我尝试从服务器 ping / 获取 200 ok,如果失败,则切换到第二个 URL。但是有些情况是服务器启动并运行,返回 200 OK,但 API 无法访问。我的主要问题是我看不到如何捕获错误并使用库中的另一个 URL 重新运行方法。