class Elementary::Middleware::RaiseOnStatus

Raise an exception for certain HTTP response status codes

Examples

Faraday.new do |conn|
  conn.request :raise_on_status
  conn.adapter ...
end

The above example will raise an HttpStatusError if the response contains a code in the range 300 through 600.

You can also pair this with the retry middleware to attempt to recover from intermittent failures…

Faraday.new do |conn|
  conn.request :retry, max: 2, interval: 0.05,
                       interval_randomness: 0.5, backoff_factor: 2
                       exceptions: [Faraday::TimeoutError, SecurityEvents::HttpStatusError]
  conn.request :raise_on_status
  conn.adapter ...
end

This example will do the same as the first, but the exception will be caught by the retry middleware and the request will be executed up to two more times before raising. NOTE: Middleware order matters here!

Constants

DEFAULT_STATUS_ARRAY
ERROR_HEADER_CODE
ERROR_HEADER_MSG

Public Class Methods

new(app) click to toggle source

Public: Initialize middleware

Calls superclass method
# File lib/elementary/middleware/raise_on_status.rb, line 66
def initialize(app)
  super(app)
  status_array ||= DEFAULT_STATUS_ARRAY
  @status_set = status_option_array_to_set(status_array)
end

Public Instance Methods

call(request_env) click to toggle source
# File lib/elementary/middleware/raise_on_status.rb, line 72
def call(request_env)
  begin
    @app.call(request_env).on_complete do |response_env|
      status = response_env[:status]
      if @status_set.include? status
        error_opts = {
            :status_code => status,
            :method => response_env.method.to_s.upcase,
            :url => response_env.url.to_s
        }
        headers = response_env[:response_headers]
        if headers.include?(ERROR_HEADER_CODE) && headers.include?(ERROR_HEADER_MSG)
          error_opts[:header_message] = headers[ERROR_HEADER_MSG]
          error_opts[:header_code] = headers[ERROR_HEADER_CODE]
          raise Elementary::Errors::RPCFailure, error_opts
        else
          raise HttpStatusError, error_opts
        end
      end
    end
  rescue Faraday::ClientError => e
    raise HttpStatusError, :parent_message => e.message
  end
end

Private Instance Methods

status_option_array_to_set(status_array) click to toggle source

Private: Construct a set of status codes.

Accepts an array of Numeric and Enumerable objects which are added or merged to form a set.

# File lib/elementary/middleware/raise_on_status.rb, line 102
def status_option_array_to_set(status_array)
  set = Set.new
  status_array.each do |item|
    set.add item if item.is_a? Numeric
    set.merge item if item.is_a? Enumerable
  end
  set
end