Class: Faraday::Conductivity::SelectiveErrors
- Inherits:
-
Middleware
- Object
- Middleware
- Faraday::Conductivity::SelectiveErrors
- Defined in:
- lib/faraday/conductivity/selective_errors.rb
Overview
Use this to raise errors on certain HTTP statuses. These are basically the same errors as Faraday raises when you use the “raise_error” middleware, but with added fields to better inspect what went wrong.
Examples:
# specify an array
faraday.response :selective_errors, on: [422,500]
# or a range:
faraday.response :selective_errors, on: 500...600
# specify errors:
faraday.response :selective_errors, except: [404,422]
Rescueing the errors:
begin
do_request
rescue Faraday::Conductivity::Error => error
puts error.request[:url]
puts error.request[:method]
puts error.request[:body]
puts error.request[:headers]
puts error.response[:status]
puts error.response[:body]
puts error.response[:headers]
end
Constant Summary collapse
- ClientErrorStatuses =
400...600
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, options = {}) ⇒ SelectiveErrors
constructor
A new instance of SelectiveErrors.
- #should_raise_error?(status) ⇒ Boolean
Constructor Details
#initialize(app, options = {}) ⇒ SelectiveErrors
Returns a new instance of SelectiveErrors.
59 60 61 62 63 |
# File 'lib/faraday/conductivity/selective_errors.rb', line 59 def initialize(app, = {}) @app = app @on = .fetch(:on) { ClientErrorStatuses } @except = .fetch(:except) { [] } end |
Instance Method Details
#call(env) ⇒ Object
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'lib/faraday/conductivity/selective_errors.rb', line 65 def call(env) # capture request because it will be modified during the request request = { :method => env[:method], :url => env[:url], :body => env[:body], :headers => env[:request_headers], } start_time = Time.now @app.call(env).on_complete do status = env[:status] if should_raise_error?(status) response = { :status => env[:status], :body => env[:body], :headers => env[:response_headers], } error = case status when 404 Faraday::Error::ResourceNotFound.new(response) when 407 # mimic the behavior that we get with proxy requests with HTTPS Faraday::Error::ConnectionFailed.new(%{407 "Proxy Authentication Required "}) else Faraday::Error::ClientError.new(response) end error.extend Error error.response = response error.request = request error.response_time = Time.now - start_time raise error end end end |
#should_raise_error?(status) ⇒ Boolean
106 107 108 |
# File 'lib/faraday/conductivity/selective_errors.rb', line 106 def should_raise_error?(status) @on.include?(status) && !@except.include?(status) end |