Looking for Example of Faraday Middleware with Error checking

user3084728 picture user3084728 · Dec 30, 2013 · Viewed 12.1k times · Source

I am looking for an example of Faraday Middleware that handles http (status code) errors on requests and additionally network timeouts.

After reading the docs for Faraday and it's middleware it's my understanding that this is one of middleware's use cases… I just have no idea what an implementation is supposed to look like.

Thanks

Answer

Peter Souter picture Peter Souter · Jan 7, 2014

Faraday has an error handling middleware in by default:

faraday.use Faraday::Response::RaiseError

For example:

require 'faraday'

conn = Faraday.new('https://github.com/') do |c|
  c.use Faraday::Response::RaiseError
  c.use Faraday::Adapter::NetHttp
end

response = conn.get '/cant-find-me' 
#=> gems/faraday-0.8.8/lib/faraday/response/raise_error.rb:6:in `on_complete': the server responded with status 404 (Faraday::Error::ResourceNotFound)

If you want to write your own middleware to handle HTTP status code responses, heres a basic example:

require 'faraday'

class CustomErrors < Faraday::Response::Middleware
  def on_complete(env)
    case env[:status]
    when 404
      raise RuntimeError, 'Custom 404 response'
    end
  end
end

conn = Faraday.new('https://github.com/') do |c|
  c.use CustomErrors
  c.use Faraday::Adapter::NetHttp
end

response = conn.get '/cant-find-me' #=> `on_complete': Custom 404 response (RuntimeError)

For your code, you'll probably want to put it in a separate file, require it, modularise it etc.

If you want to see a good live example, the new Instagram gem has a pretty good setup to raise custom errors: GitHub link