Handle Faraday::Error::ConnectionFailed with middleware
source link: https://www.sethvargo.com/handle-faradayerrorconnection-failed-with-middleware/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Faraday is a really nice, middleware-based HTTP client for Ruby. For simple libraries, I recommend HTTParty, but Faraday is a really awesome solution when you need full control over the complete stack.
However, Faraday has one feature/flaw that I have found. If Faraday is unable to connect to a server, it throws a really nasty error. I whipped up a tiny middleware to handle this error:
class Middleware::Exceptions < Faraday::Middleware
def call(env)
begin
@app.call(env)
rescue Faraday::Error::ConnectionFailed => e
# Do whatever to handle your error here, maybe raise a more semantic error
end
end
end
And then tell Faraday to use this middleware:
Faraday.new(endpoint) do |connection|
connection.use Middleware::Exceptions
end
In my projects, I typically do something like:
rescue Faraday::Error::ConnectionFailed => e
url = env[:url].to_s.gsub(env[:url].path, '')
$stderr.puts "The server at #{url} is either unavailable or is not currently accepting requests. Please try again in a few minutes."
end
Happy error handling!
About Seth
Seth Vargo is an engineer at Google. Previously he worked at HashiCorp, Chef Software, CustomInk, and some Pittsburgh-based startups. He is the author of Learning Chef and is passionate about reducing inequality in technology. When he is not writing, working on open source, teaching, or speaking at conferences, Seth advises non-profits.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK