Sha256: aa1b6c7d59772d0d37031ea90301493eb214127bf955a43410e98bc469c6e3a2

Contents?: true

Size: 1.47 KB

Versions: 8

Compression:

Stored size: 1.47 KB

Contents

# frozen_string_literal: true

module OAuth2
  class Error < StandardError
    attr_reader :response, :code, :description

    # standard error codes include:
    # 'invalid_request', 'invalid_client', 'invalid_token', 'invalid_grant', 'unsupported_grant_type', 'invalid_scope'
    def initialize(response)
      @response = response
      message_opts = {}

      if response.parsed.is_a?(Hash)
        @code = response.parsed['error']
        @description = response.parsed['error_description']
        message_opts = parse_error_description(@code, @description)
      end

      super(error_message(response.body, message_opts))
    end

  private

    def error_message(response_body, opts = {})
      lines = []

      lines << opts[:error_description] if opts[:error_description]

      error_string = if response_body.respond_to?(:encode) && opts[:error_description].respond_to?(:encoding)
                       script_encoding = opts[:error_description].encoding
                       response_body.encode(script_encoding, invalid: :replace, undef: :replace)
                     else
                       response_body
                     end

      lines << error_string

      lines.join("\n")
    end

    def parse_error_description(code, description)
      return {} unless code || description

      error_description = ''
      error_description += "#{code}: " if code
      error_description += description if description

      {error_description: error_description}
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
oauth2-2.0.4 lib/oauth2/error.rb
oauth2-2.0.3 lib/oauth2/error.rb
oauth2-2.0.2 lib/oauth2/error.rb
oauth2-2.0.1 lib/oauth2/error.rb
oauth2-2.0.0 lib/oauth2/error.rb
oauth2-2.0.0.rc3 lib/oauth2/error.rb
oauth2-2.0.0.rc2 lib/oauth2/error.rb
oauth2-2.0.0.rc1 lib/oauth2/error.rb