Check HTTP response status code. Raise error if the status is not 2xx.

 @param [Hurley::Response] response Web API response.
435801
def check_response_status_code(response)
      case response.status_code
      when 200..300
        # Do-nothing
      when 301, 302, 303, 307
        raise GoogleMapsService::Error::RedirectError.new(response), sprintf('Redirect to %s', response.header[:location])
      when 401
        raise GoogleMapsService::Error::ClientError.new(response), 'Unauthorized'
      when 304, 400, 402...500
        raise GoogleMapsService::Error::ClientError.new(response), 'Invalid request'
      when 500..600
        raise GoogleMapsService::Error::ServerError.new(response), 'Server error'
      end
    end
728255
def check_status(response):
    ''''''
    status = response.status_code
    if status < 300:
        return
    exception = {
        400: exceptions.BadQuery,
        401: exceptions.InvalidAPIKey,
        403: exceptions.NoPermission,
        404: exceptions.MissingResource,
        429: exceptions.TooManyRequests,
        500: exceptions.ServerError
    }.get(status, None)

    # differentiate between over quota and rate-limiting
    if status == 429 and 'quota' in response.text.lower():
        exception = exceptions.OverQuota

    if exception:
        raise exception(response.text)

    raise exceptions.APIException('%s: %s' % (status, response.text))
245886
def convert_response(response)
      HttpResponse.new(response.status, response.headers, response.body)
    end
558144
def handle_itc_response(raw, flaky_api_call: false)
      return unless raw
      return unless raw.kind_of?(Hash)

      data = raw['data'] || raw # sometimes it's with data, sometimes it isn't

      error_keys = ["sectionErrorKeys", "validationErrors", "serviceErrors"]
      info_keys = ["sectionInfoKeys", "sectionWarningKeys"]
      error_and_info_keys_to_check = error_keys + info_keys

      errors_in_data = fetch_errors_in_data(data_section: data, keys: error_and_info_keys_to_check)
      errors_in_version_info = fetch_errors_in_data(data_section: data, sub_section_name: "versionInfo", keys: error_and_info_keys_to_check)

      # If we have any errors or "info" we need to treat them as warnings or errors
      if errors_in_data.count == 0 && errors_in_version_info.count == 0
        logger.debug("Request was successful")
      end

      # We pass on the `current_language` so that the error message tells the user
      # what language the error was caused in
      handle_response_hash = lambda do |hash, current_language = nil|
        errors = []
        if hash.kind_of?(Hash)
          current_language ||= hash["language"]

          hash.each do |key, value|
            errors += handle_response_hash.call(value, current_language)

            next unless key == 'errorKeys' && value.kind_of?(Array) && value.count > 0
            # Prepend the error with the language so it's easier to understand for the user
            errors += value.collect do |current_error_message|
              current_language ? "[#{current_language}]: #{current_error_message}" : current_error_message
            end
          end
        elsif hash.kind_of?(Array)
          hash.each do |value|
            errors += handle_response_hash.call(value)
          end
          # else: We don't care about simple values
        end
        return errors
      end

      errors = handle_response_hash.call(data)

      # Search at data level, as well as "versionInfo" level for errors
      errors_in_data = fetch_errors_in_data(data_section: data, keys: error_keys)
      errors_in_version_info = fetch_errors_in_data(data_section: data, sub_section_name: "versionInfo", keys: error_keys)

      errors += errors_in_data.values if errors_in_data.values
      errors += errors_in_version_info.values if errors_in_version_info.values
      errors = errors.flat_map { |value| value }

      # Sometimes there is a different kind of error in the JSON response
      # e.g. {"warn"=>nil, "error"=>["operation_failed"], "info"=>nil}
      different_error = raw.fetch('messages', {}).fetch('error', nil)
      errors << different_error if different_error

      if errors.count > 0 # they are separated by `.` by default
        # Sample `error` content: [["Forbidden"]]
        if errors.count == 1 && errors.first == "You haven't made any changes."
          # This is a special error which we really don't care about
        elsif errors.count == 1 && errors.first.include?("try again later")
          raise ITunesConnectTemporaryError.new, errors.first
        elsif errors.count == 1 && errors.first.include?("Forbidden")
          raise_insufficient_permission_error!
        elsif flaky_api_call
          raise ITunesConnectPotentialServerError.new, errors.join(' ')
        else
          raise ITunesConnectError.new, errors.join(' ')
        end
      end

      # Search at data level, as well as "versionInfo" level for info and warnings
      info_in_data = fetch_errors_in_data(data_section: data, keys: info_keys)
      info_in_version_info = fetch_errors_in_data(data_section: data, sub_section_name: "versionInfo", keys: info_keys)

      info_in_data.each do |info_key, info_value|
        puts(info_value)
      end

      info_in_version_info.each do |info_key, info_value|
        puts(info_value)
      end

      return data
    end
725861
def _handle_response(self, response):
        
        if not str(response.status_code).startswith('2'):
            raise build_api_error(response)
        return response
1194389
def _check_response(self, response):
        
        if response.status_code > 299 or response.status_code < 200:
            log.debug("Received response code [%s] - headers: %s" % (response.status_code, str(response.headers)))
            try:
                _json = response.json()
                err_type = _json.get("error", '')
                if err_type == 'RecordNotFound':
                    raise RecordNotFoundException(json.dumps(_json), response=response)
                elif err_type == "TooManyValues":
                    raise TooManyValuesException(json.dumps(_json), response=response)
                else:
                    raise APIException(json.dumps(_json), response=response)
            except ValueError:
                response.raise_for_status()
1147176
def parse_response(response)
      parsed_response = JSON.parse(response.body, :symbolize_names => true)
      if response.code.to_i.between?(400,599)
        raise Monzo::APIError, "#{parsed_response[:code]}: #{parsed_response[:error]}"
      end
      parsed_response
    end
1213832
def check_response(res, options)
      if res.status >= 200 && res.status <= 299
        if(options[:mashify] && res.body.instance_of?(Hash))
          Hashie::Mash.new(res.body)
        else
          res.body
        end
      elsif [404, 410].include? res.status
        err_str = "Error processing request: (#{res.status})! #{res.env[:method]} URL: #{res.env[:url]}"
        err_str << "\n Resp Body: #{res.body}"
        raise RequestError::NotFound.new(res), err_str
      else
        err_str = "Error processing request (#{res.status})! #{res.env[:method]} URL: #{res.env[:url]}"
        err_str << "\n Resp Body: #{res.body}"
        raise RequestError.new(res), err_str
      end
    end
609413
def decode_response_body(response)
      check_response_status_code(response)
      body = MultiJson.load(response.body, :symbolize_keys => true)
      check_body_error(response, body)
      body
    end
846247
def run
      if response.is_a? @expected_response
        self.class.on_response.call(self, response)
        response.tap do
          parse_response!
        end
      else
        raise HTTPError.new(error_message, response: response)
      end
    end
662557
def parse_response_for(response)
      case response
        when Net::HTTPOK, Net::HTTPCreated then return Response::Success.new(response)
        when Net::HTTPForbidden then raise Response::InvalidCredentials
        when Net::HTTPInternalServerError then raise Response::ServerError
        else raise Response::UnknownError
      end
    end
208998
def check_for_status_code_failure(azure_response)
      fail MsRest::ValidationError, 'Azure response cannot be nil' if azure_response.nil?
      fail MsRest::ValidationError, 'Azure response cannot have empty response object' if azure_response.response.nil?
      fail MsRest::ValidationError, 'Azure response cannot have empty request object' if azure_response.request.nil?

      status_code = azure_response.response.status
      http_method = azure_response.request.method

      fail AzureOperationError, "Unexpected polling status code from long running operation #{status_code}" unless status_code === 200 || status_code === 202 ||
          (status_code === 201 && http_method === :put) ||
          (status_code === 204 && (http_method === :delete || http_method === :post))
    end
894723
def valid?(params, bool_response = true)
      requires params
      res = DataSift.request(:POST, 'push/validate', @config, params)
      bool_response ? res[:http][:status] == 200 : res
    end
472672
function RoostErrorStatus(response) {
  MessagingServiceStatus.call(this, 'roost');

  // There was an error when attempting to send message
  this.state.message = response.code ? 'Code: ' + response.code + '. ' : '';
  this.state.message += response.error;

  // Determine the correct status code
  // No code is being passed from Roost at this time, so we must depend on the error string
  if (response.error.match(/auth/g)) this.state.code = this.StatusCodes.UNAUTHORIZED;
  else if (response.error.match(/Invalid/g)) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (response.error.match(/Incorrectly formatted/g)) this.state.code = this.StatusCodes.DATA_REJECTED;
  else this.state.code = this.StatusCodes.DEFAULT;
}
1201887
def response_error!(response)
      args = [response.status.to_s, response: response]

      case response.code
      when 400..499 then raise Down::ClientError.new(*args)
      when 500..599 then raise Down::ServerError.new(*args)
      else               raise Down::ResponseError.new(*args)
      end
    end
497534
def respond(response, headers_or_body = {}, body = nil)
      raise StateError, "not in header state" if @response_state != :headers

      if headers_or_body.is_a? Hash
        headers = headers_or_body
      else
        headers = {}
        body = headers_or_body
      end

      if @keepalive
        headers[CONNECTION] = KEEP_ALIVE
      else
        headers[CONNECTION] = CLOSE
      end

      case response
      when Symbol, Fixnum, Integer
        response = Response.new(response, headers, body)
      when Response
      else raise TypeError, "invalid response: #{response.inspect}"
      end

      if current_request
        current_request.handle_response(response)
      else
        raise RequestError
      end

      # Enable streaming mode
      if response.chunked? and response.body.nil?
        @response_state = :chunked_body
      elsif @keepalive
        reset_request
      else
        @current_request = nil
        @parser.reset
        @request_fsm.transition :closed
      end
    rescue IOError, SystemCallError, RequestError
      # The client disconnected early, or there is no request
      @keepalive = false
      @request_fsm.transition :closed
      @parser.reset
      @current_request = nil
    end
326511
def check_web_status(hsh)
      status = 'invalid' if hsh[:web_neg]&.include?('error')

      if hsh[:url] && hsh[:url_f] && status.nil?
        status = hsh[:url] != hsh[:url_f] ? 'formatted' : 'unchanged'
      end

      hsh[:web_status] = status if status.present?
      hsh
    end