Sha256: 6e7a49fbfb6dd12fb52811be8f125d3e91ef2677c3bc23a4df18c8180e10bdf5

Contents?: true

Size: 1.47 KB

Versions: 2

Compression:

Stored size: 1.47 KB

Contents

# frozen_string_literal: true

module PurpleAirApi
  module V1
    # Handles any HTTP exceptions for 400 and 500 error codes
    class RaiseHttpException < Faraday::Middleware
      # A switch statement which determines which error to raise depending on error code
      def call(env)
        @app.call(env).on_complete do |response|
          self.response = response
          case response[:status].to_i
          when 400
            raise ApiError.new(error_message, parsed_response[:error], response)
          when 403
            raise ApiKeyError.new(error_message, parsed_response[:error], response)
          when 404
            raise NotFoundError.new(error_message, parsed_response[:error], response)
          when 415
            raise MissingJsonPayloadError.new(error_message, 'MissingJsonPayloadError', response)
          when 500
            raise ServerError.new(error_message, 'ServerError', response)
          end
        end
      end

      # Faraday syntax for implementing middleware
      def initialize(app)
        super app
        @parser = nil
      end

      private

      attr_accessor :response

      def error_message
        parsed_response[:description]
      end

      def parsed_response
        @parsed_response ||= FastJsonparser.parse(response[:body])
      rescue FastJsonparser::ParseError
        unknown_error_message
      end

      def unknown_error_message
        { description: 'Something went wrong in the request.' }
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
purple_air_api-0.1.1 lib/purple_air_api/V1/raise_http_exception.rb
purple_air_api-0.1.0 lib/purple_air_api/V1/raise_http_exception.rb