rubocop:disable Metrics/PerceivedComplexity
 If the response is coming from a flaky api, set flaky_api_call to true so we retry a little.
 Patience is a virtue.
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
1325797
def _handle_rate_exceeded(self, response):  # pragma: no cover
        """"""
        waiting_time = int(response.headers.get("Retry-After", 10))
        time.sleep(waiting_time)
60352
def handle_response(response)
      return super(response)
    rescue ActiveResource::ClientError => exc
      begin
        # ugly code to insert the error_message into response
        error_message = "#{format.decode response.body}"
        if not error_message.nil? or error_message == ""
          exc.response.instance_eval do ||
            @message = error_message
          end
        end
      ensure
        raise exc
      end
    end
1365669
def respond_via_request(self, task):
        
        warn(f"Detected slow response into webhook. "
             f"(Greater than {RESPONSE_TIMEOUT} seconds)\n"
             f"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.",
             TimeoutWarning)

        dispatcher = self.get_dispatcher()
        loop = dispatcher.loop

        try:
            results = task.result()
        except Exception as e:
            loop.create_task(
                dispatcher.errors_handlers.notify(dispatcher, types.Update.get_current(), e))
        else:
            response = self.get_response(results)
            if response is not None:
                asyncio.ensure_future(response.execute_response(dispatcher.bot), loop=loop)
462027
def handle_response(r)
      return true if @done
      @raw_response = r
      res = result_from(r)
      if res.success?
        if @cancel_timer
          @cancel_timer.cancel
          @cancel_timer = nil
        end
        @done = true
        succeed(res.content)
      else
        reason = res.content
        if res.non_delivery?
          Log.info("Request non-delivery (#{reason}) for #{@operation}")
        elsif res.retry?
          reason = (reason && !reason.empty?) ? reason : "RightScale not ready"
          Log.info("Request #{@operation} failed (#{reason}) and should be retried")
        elsif res.cancel?
          reason = (reason && !reason.empty?) ? reason : "RightScale cannot execute request"
          Log.info("Request #{@operation} canceled (#{reason})")
        else
          Log.info("Request #{@operation} failed (#{reason})")
        end
        if (res.non_delivery? || res.retry? || @retry_on_error) && !res.cancel?
          Log.info("Retrying in #{@retry_delay} seconds...")
          if @retry_delay > 0
            this_delay = @retry_delay
            if (@retries += 1) >= @retry_delay_count
              @retry_delay = [@retry_delay * RETRY_BACKOFF_FACTOR, @max_retry_delay].min
              @retry_delay_count = [@retry_delay_count / RETRY_BACKOFF_FACTOR, 1].max
              @retries = 0
            end
            EM.add_timer(this_delay) { run }
          else
            EM.next_tick { run }
          end
        else
          cancel(res.content)
        end
      end
      true
    end
663646
def fetch
      response = process_http_request
      response.body.to_s
    rescue StandardError => error
      ProxyFetcher.logger.warn("Failed to process request to #{url} (#{error.message})")
      ''
    end
1371870
def __cache_response(self, cache_key, res, method):
        
        if ('expires' in res.headers
                and method not in self.__uncached_methods__):
            cache_timeout = get_cache_time_left(res.headers.get('expires'))

            # Occasionally CCP swagger will return an outdated expire
            # warn and skip cache if timeout is <0
            if cache_timeout >= 0:
                self.cache.set(
                    cache_key,
                    CachedResponse(
                        status_code=res.status_code,
                        headers=res.headers,
                        content=res.content,
                        url=res.url,
                    ),
                )
            else:
                LOGGER.warning(
                    "[%s] returned expired result: %s", res.url,
                    res.headers)
                warnings.warn("[%s] returned expired result" % res.url)
1351601
async def Resolved(self, retry, unit_name):
        '''
        
        '''
        # map input types to rpc msg
        _params = dict()
        msg = dict(type='Client',
                   request='Resolved',
                   version=1,
                   params=_params)
        _params['retry'] = retry
        _params['unit-name'] = unit_name
        reply = await self.rpc(msg)
        return reply
1129826
def handle_response(response)
      type, msgid, error, result = response
      if observable = @requests[msgid]
        @requests[msgid].set_response(result, error)
      else
        warn "unknown response with id=#{msgid}"
      end
    end
182531
def core__send_request_fail(error, payload: nil)
      response = { result: false, error_message: error }
      response[:payload] = payload if payload
      render json: response
    end
282459
private static void apiReady() {

        loadingApi = false;
        for (Command callback : onApiReady) {
            callback.execute();
        }
        onApiReady.clear();
    }
584741
def on_complete(response)
      return if response[:body].nil?

      case response[:body][:status].to_i
      when 400
        raise Readmill::BadRequest, error_message(response)
      when 401
        raise Readmill::Unauthorized, error_message(response)
      when 403
        raise Readmill::Forbidden, error_message(response)
      when 404
        raise Readmill::NotFound, error_message(response)
      when 500
        raise Readmill::InternalServerError, error_message(response)
      when 504
        raise Readmill::GatewayTimeout, error_message(response)
      end
    end
1267052
def is_rate_limited(response):
        
        if (response.status_code == codes.too_many_requests and 'Retry-After' in response.headers and
                int(response.headers['Retry-After']) >= 0):
            return True

        return False
656675
def _handle_offset_error(self, failure):
        
        # outstanding request got errback'd, clear it
        self._request_d = None

        if self._stopping and failure.check(CancelledError):
            # Not really an error
            return
        # Do we need to abort?
        if (self.request_retry_max_attempts != 0 and
                self._fetch_attempt_count >= self.request_retry_max_attempts):
            log.debug(
                "%r: Exhausted attempts: %d fetching offset from kafka: %r",
                self, self.request_retry_max_attempts, failure)
            self._start_d.errback(failure)
            return
        # Decide how to log this failure... If we have retried so many times
        # we're at the retry_max_delay, then we log at warning every other time
        # debug otherwise
        if (self.retry_delay < self.retry_max_delay or
                0 == (self._fetch_attempt_count % 2)):
            log.debug("%r: Failure fetching offset from kafka: %r", self,
                      failure)
        else:
            # We've retried until we hit the max delay, log at warn
            log.warning("%r: Still failing fetching offset from kafka: %r",
                        self, failure)
        self._retry_fetch()
833399
def _process_response(response):
        
        if response.status_code == 404:
            raise Trovebox404Error("HTTP Error %d: %s" %
                                   (response.status_code, response.reason))
        try:
            json_response = response.json()
            code = json_response["code"]
            message = json_response["message"]
        except (ValueError, KeyError):
            # Response wasn't Trovebox JSON - check the HTTP status code
            if 200 <= response.status_code < 300:
                # Status code was valid, so just reraise the exception
                raise
            else:
                raise TroveboxError("HTTP Error %d: %s" %
                                    (response.status_code, response.reason))

        if 200 <= code < 300:
            return json_response
        elif (code == DUPLICATE_RESPONSE["code"] and
               DUPLICATE_RESPONSE["message"] in message):
            raise TroveboxDuplicateError("Code %d: %s" % (code, message))
        else:
            raise TroveboxError("Code %d: %s" % (code, message))
249061
private void processResponseWrapper(Response response, boolean isFailure) {
        try {
            ResponseImpl responseImpl = (ResponseImpl)response;
            if (isFailure || !responseImpl.isRedirect()) {
                processResponse(response);
            } else {
                processRedirectResponse(response);
            }
        } catch (Throwable t) {
            logger.error("processResponseWrapper caught exception: " + t.getLocalizedMessage());
            listener.onFailure(response, t, null);
        }
    }
884263
def _after_request(self, response):
        
        # Do not trace if the url is blacklisted
        if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):
            return response

        try:
            tracer = execution_context.get_opencensus_tracer()
            tracer.add_attribute_to_current_span(
                HTTP_STATUS_CODE,
                str(response.status_code))
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
        finally:
            return response