a method to catch and report http options request connectivity errors
546901
def _options_request(self, url, **kwargs):
        
        '''  '''
        
    # construct request kwargs
        request_kwargs = {
            'method': 'OPTIONS',
            'url': url
        }
        for key, value in kwargs.items():
            request_kwargs[key] = value

    # send request and handle response
        return self._request(**request_kwargs)
1305476
function HTTPOptions(options) {
  if (!(this instanceof HTTPOptions))
    return new HTTPOptions(options);

  this.network = Network.primary;
  this.logger = null;
  this.node = null;
  this.apiKey = base58.encode(random.randomBytes(20));
  this.apiHash = digest.hash256(Buffer.from(this.apiKey, 'ascii'));
  this.noAuth = false;

  this.prefix = null;
  this.host = '127.0.0.1';
  this.port = 8080;
  this.ssl = false;
  this.keyFile = null;
  this.certFile = null;

  this.fromOptions(options);
}
1178305
function(options, cb, onError) {
    var self = this;

    options = options || {};
    this._options = {
        host: options.host || '127.0.0.1',
        vhost: options.vhost || '/',
        port: options.port || 5672,
        login : options.login || 'guest',
        password : options.password || 'guest',
        exchange: options.exchange || 'nameko-rpc',
        timeout: options.timeout || 5000,
        reconnect: typeof options.reconnect === 'undefined' ? true : options.reconnect
    };

    if (options.logger) {
        this.logger = options.logger;
    } else {
        this.logger = winston;
        winston.level = options.debug_level || 'info';
    }

    this.logger.debug('Creating Nameko client');

    this._conn = amqp.createConnection({
        host: this._options.host,
        vhost: this._options.vhost,
        port: this._options.port,
        login: this._options.login,
        password: this._options.password,
        port: this._options.port
    }, {
        reconnect: this._options.reconnect
    });

    this._conn.on('error', function(e) {
        self.logger.error('AMQP error:', e.stack);
        onError(e);
    });

    this._requests = {};

    this._conn.once('ready', function() {
        self.logger.debug('Connected to %s:%d', self._options.host, self._options.port);

        self._exchange = self._conn.exchange(
            self._options.exchange,
            {
                // TODO: can we somehow mirror exchange settings from RabbitMQ?
                type: 'topic',
                durable: true,
                autoDelete: false
            }
        );
        self._exchange.removeAllListeners('error').on('error', function(e) {
            self.logger.error('Exchange error: %s', e);
            onError(e.stack);
        });
        self._exchange.removeAllListeners('open').on('open', function() {
            self.logger.debug('Selected exchange %s', self._options.exchange);

            self._responseQueueName = 'rpc-node-response-' + uuid.v4();
            var ctag;

            var replyQueue = self._conn.queue(self._responseQueueName, {
                exclusive: true
            }, function(replyQueue) {
                self.logger.debug('Connected to reply queue %s', self._responseQueueName);

                replyQueue.bind(self._options.exchange, self._responseQueueName);

                replyQueue.subscribe(function(message, headers, deliveryInfo, messageObject) {
                    cid = messageObject.correlationId;
                    request = self._requests[cid];
                    if (request) {
                        self.logger.debug('[%s] Received response', cid);
                        clearTimeout(request.timeout);
                        if (!message.error) {
                            request.onSuccess(message.result);
                        } else {
                            request.onError(new Error(`${message.error.exc_path}: ${message.error.value}`));
                        }
                    } else {
                        self.logger.error('[%s] Received response with unknown cid!', cid);
                    }
                    delete self._requests[cid];
                }).addCallback(function(ok) {
                    ctag = ok.consumerTag;

                    self.logger.debug('Nameko client ready!');

                    self.emit('ready', self);
                    cb && cb(self);
                });
            });
        });
    });
}
188546
function logHttpRequestError (uniqueId, err) {
    // require log client
    if (!logClient) {
        return
    }
    // log error
    logClient.log('httpRequestError', {
        httpRequestId: uniqueId.id,
        httpRequestErrorCreateTime: microTimestamp(),
        httpRequestError: err.message,
    })
}
262165
public void queryError(OutputStream os,
                         HeadersAmp headers,
                         String address,
                         long qId,
                         Throwable exn)
    throws IOException
  {
    init(os);

    OutH3 out = _out;

    if (out == null)
      return;

    if (log.isLoggable(_level)) {
      log.log(_level, "query-error " + exn
                 + " (in " + this + ")" + " {to:" + address + ", " + headers + "}");
      
      if (log.isLoggable(Level.FINEST)) {
        log.log(Level.FINEST, exn.toString(), exn);
      }
    }

    try {
      out.writeLong(MessageTypeHamp.QUERY_ERROR.ordinal());
      writeHeaders(out, headers);
      
      writeToAddress(out, address);
      out.writeLong(qId);

      ErrorAmp error = ErrorAmp.create(exn);

      out.writeString(error.getCode().toString());
      out.writeString(error.getMessage());
      out.writeObject(error.getDetail());

      // XXX: out.flushBuffer();
    } catch (Throwable e) {
      log.log(Level.WARNING, e.toString(), e);
      
      throw e;
    }
  }
662835
def http_error(self, url, fp, errcode, errmsg, headers, data=None):
        """"""
        # First check if there's a specific handler for this error
        name = 'http_error_%d' % errcode
        if hasattr(self, name):
            method = getattr(self, name)
            if data is None:
                result = method(url, fp, errcode, errmsg, headers)
            else:
                result = method(url, fp, errcode, errmsg, headers, data)
            if result: return result
        return self.http_error_default(url, fp, errcode, errmsg, headers)
708328
def HandleExceptionsAndRebuildHttpConnections(retry_args):
    
    # If the server indicates how long to wait, use that value.  Otherwise,
    # calculate the wait time on our own.
    retry_after = None

    # Transport failures
    if isinstance(retry_args.exc, (http_client.BadStatusLine,
                                   http_client.IncompleteRead,
                                   http_client.ResponseNotReady)):
        logging.debug('Caught HTTP error %s, retrying: %s',
                      type(retry_args.exc).__name__, retry_args.exc)
    elif isinstance(retry_args.exc, socket.error):
        logging.debug('Caught socket error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, socket.gaierror):
        logging.debug(
            'Caught socket address error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, socket.timeout):
        logging.debug(
            'Caught socket timeout error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, httplib2.ServerNotFoundError):
        logging.debug(
            'Caught server not found error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, ValueError):
        # oauth2client tries to JSON-decode the response, which can result
        # in a ValueError if the response was invalid. Until that is fixed in
        # oauth2client, need to handle it here.
        logging.debug('Response content was invalid (%s), retrying',
                      retry_args.exc)
    elif (isinstance(retry_args.exc, TokenRefreshError) and
          hasattr(retry_args.exc, 'status') and
          (retry_args.exc.status == TOO_MANY_REQUESTS or
           retry_args.exc.status >= 500)):
        logging.debug(
            'Caught transient credential refresh error (%s), retrying',
            retry_args.exc)
    elif isinstance(retry_args.exc, exceptions.RequestError):
        logging.debug('Request returned no response, retrying')
    # API-level failures
    elif isinstance(retry_args.exc, exceptions.BadStatusCodeError):
        logging.debug('Response returned status %s, retrying',
                      retry_args.exc.status_code)
    elif isinstance(retry_args.exc, exceptions.RetryAfterError):
        logging.debug('Response returned a retry-after header, retrying')
        retry_after = retry_args.exc.retry_after
    else:
        raise retry_args.exc
    RebuildHttpConnections(retry_args.http)
    logging.debug('Retrying request to url %s after exception %s',
                  retry_args.http_request.url, retry_args.exc)
    time.sleep(
        retry_after or util.CalculateWaitForRetry(
            retry_args.num_retries, max_wait=retry_args.max_retry_wait))
912156
private static void ensureStatusOk(HttpResponse<String> response) throws ClientErrorException,
            ServerErrorException, OtherCommunicationException {
        int responseStatus = response.getStatus();
        if (isClientError(responseStatus)) {
            throw new ClientErrorException(response.getBody());
        } else if (isServerError(responseStatus)) {
            throw new ServerErrorException();
        } else if (isOtherErrorResponse(responseStatus)) {
            throw new OtherCommunicationException();
        }
    }
106591
function HttpError(message, status, cause) {
    this.status = status || StatusCode.UNKNOWN;
    HttpError.super_.call(this, errors.ErrorCode.HTTP + this.status, message || StatusLine[this.status] || StatusLine[StatusCode.UNKNOWN], cause);
}
1196485
def catch_error(func):
    """"""
    import amqp
    try:
        import pika.exceptions
        connect_exceptions = (
            pika.exceptions.ConnectionClosed,
            pika.exceptions.AMQPConnectionError,
        )
    except ImportError:
        connect_exceptions = ()

    connect_exceptions += (
        select.error,
        socket.error,
        amqp.ConnectionError
    )

    def wrap(self, *args, **kwargs):
        try:
            return func(self, *args, **kwargs)
        except connect_exceptions as e:
            logging.error('RabbitMQ error: %r, reconnect.', e)
            self.reconnect()
            return func(self, *args, **kwargs)
    return wrap
296464
def handle_request_parsing_error(
        err,
        _req,
        _schema,
        _err_status_code,
        _err_headers,
):
    
    abort(HTTPStatus.BAD_REQUEST, errors=err.messages)
1156485
protected void handleError(URI requestUri, HttpMethod requestMethod, int statusCode, String statusMessage,
            ByteSource errorBody) throws RestEndpointIOException {
        throw new RestEndpointException(requestUri, requestMethod, statusCode, statusMessage, errorBody);
    }
493530
def catch_websocket_connection_errors():
  """"""
  try:
    yield
  except websocket.WebSocketConnectionClosedException:
    raise ConnectionError("Connection already closed. SC2 probably crashed. "
                          "Check the error log.")
  except websocket.WebSocketTimeoutException:
    raise ConnectionError("Websocket timed out.")
  except socket.error as e:
    raise ConnectionError("Socket error: %s" % e)
612545
function connectionError(response, message, body) {
  var content = errorContent(ErrorType.connection, message, body);
  send(response, content, StatusCode.badGateway);
}
33298
private static void checkResponseCode(URLConnection uc) throws IOException {
        if (uc instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) uc;
            int rc = httpConnection.getResponseCode();
            if (rc != HttpURLConnection.HTTP_OK && rc != HttpURLConnection.HTTP_MOVED_TEMP) {
                throw new IOException();
            }
        }
    }
611566
private HttpURLConnection getURLConnection(String str)
            throws MalformedURLException {
        try {

            if (isHttps) {
                /* when communicating with the server which has unsigned or invalid
                * certificate (https), SSLException or IOException is thrown.
                * the following line is a hack to avoid that
                */
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
                if (isProxy) {
                    System.setProperty("https.proxyHost", proxyHost);
                    System.setProperty("https.proxyPort", proxyPort + "");
                }
            }
            else
            {
                if (isProxy)
                {
                    System.setProperty("http.proxyHost", proxyHost);
                    System.setProperty("http.proxyPort", proxyPort  + "");
                }
            }

            URL url = new URL(str);
            HttpURLConnection uc = (HttpURLConnection)url.openConnection();

            // if this header has not been set by a request set the user agent.
            if (headers == null ||
                    (headers != null &&  headers.get("user-agent") == null)) {
                // set user agent to mimic a common browser
                String ua="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)";
                uc.setRequestProperty("user-agent", ua);
            }

            uc.setInstanceFollowRedirects(false);

            return uc;
        }
        catch (MalformedURLException me)
        {
            throw new MalformedURLException(str + " is not a valid URL");
        }
        catch (Exception e)
        {
            throw new RuntimeException("Unknown error creating UrlConnection: " + e);
        }
    }
657372
def _try_options(options, exceptions,
                 jid, metadata, negotiation_timeout, loop, logger):
    
    for host, port, conn in options:
        logger.debug(
            "domain %s: trying to connect to %r:%s using %r",
            jid.domain, host, port, conn
        )
        try:
            transport, xmlstream, features = yield from conn.connect(
                loop,
                metadata,
                jid.domain,
                host,
                port,
                negotiation_timeout,
                base_logger=logger,
            )
        except OSError as exc:
            logger.warning(
                "connection failed: %s", exc
            )
            exceptions.append(exc)
            continue

        logger.debug(
            "domain %s: connection succeeded using %r",
            jid.domain,
            conn,
        )

        if not metadata.sasl_providers:
            return transport, xmlstream, features

        try:
            features = yield from security_layer.negotiate_sasl(
                transport,
                xmlstream,
                metadata.sasl_providers,
                negotiation_timeout=None,
                jid=jid,
                features=features,
            )
        except errors.SASLUnavailable as exc:
            protocol.send_stream_error_and_close(
                xmlstream,
                condition=errors.StreamErrorCondition.POLICY_VIOLATION,
                text=str(exc),
            )
            exceptions.append(exc)
            continue
        except Exception as exc:
            protocol.send_stream_error_and_close(
                xmlstream,
                condition=errors.StreamErrorCondition.UNDEFINED_CONDITION,
                text=str(exc),
            )
            raise

        return transport, xmlstream, features

    return None