Sha256: 43f8de9a78dc839e37e10b4598849f85fb6e4803ea42ea5f6c50e5d142582d9e

Contents?: true

Size: 1.26 KB

Versions: 3

Compression:

Stored size: 1.26 KB

Contents

require 'faraday'
require 'multi_json'

module Faraday
  class Response::RaiseReshapeApiError < Response::Middleware
    def on_complete(response)
      case response[:status].to_i
      when 400
        raise Reshape::BadRequest, error_message(response)
      when 401
        raise Reshape::Unauthorized, error_message(response)
      when 403
        raise Reshape::Forbidden, error_message(response)
      when 404
        raise Reshape::NotFound, error_message(response)
      when 406
        raise Reshape::NotAcceptable, error_message(response)
      when 422
        raise Reshape::UnprocessableEntity, error_message(response)
      when 500
        raise Reshape::InternalServerError, error_message(response)
      when 502
        raise Reshape::BadGateway, error_message(response)
      when 503
        raise Reshape::ServiceUnavailable, error_message(response)
      end
    end

    def error_message(response)
      message = if (body = response[:body]) && !body.empty?
        if body.is_a?(String)
          body = MultiJson.load(body, :symbolize_keys => true)
        end
        ": #{body[:error] || body[:message] || ''}"
      else
        ''
      end
      "#{response[:method].to_s.upcase} #{response[:url].to_s}: #{response[:status]}#{message}"
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
reshape-0.2 lib/faraday/response/raise_reshape_api_error.rb
reshape-0.1.1 lib/faraday/response/raise_reshape_api_error.rb
reshape-0.1 lib/faraday/response/raise_reshape_api_error.rb