Handle Faraday::Error::ConnectionFailed with middleware

Faraday, Ruby Posted on

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 a Distinguished Software 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.