Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for Example of Faraday Middleware with Error checking

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

like image 590
user3084728 Avatar asked Dec 30 '13 17:12

user3084728


1 Answers

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

like image 159
Peter Souter Avatar answered Oct 13 '22 00:10

Peter Souter