Check the connection for an error response from APNS
334794
private function checkForErrorResponse()
	{
		// Check if there is something to read from the socket
		$errorResponse = fread($this->getConnection(), self::ERROR_RESPONSE_SIZE);
		if (false !== $errorResponse && self::ERROR_RESPONSE_SIZE === strlen($errorResponse))
		{
			// Got an error, disconnect
			$this->disconnect();

			// Decode the error response
			$errorMessage = unpack('Ccommand/Cstatus/Nidentifier', $errorResponse);

			// Validate the message
			if (self::ERROR_RESPONSE_COMMAND != $errorMessage['command']) {
				throw new \RuntimeException('APNS responded with corrupt errormessage.');
			}

			// Mark the message that triggered the error as failed
			$failedMessageEnvelope = $this->retrieveMessageEnvelope($errorMessage['identifier']);
			if (null != $failedMessageEnvelope)
			{
				$failedMessageEnvelope->setStatus($errorMessage['status']);
				$this->logger->warning('Failed to send message #' . $failedMessageEnvelope->getIdentifier() . ' "' . $failedMessageEnvelope->getStatusDescription() . '" to device "' . $failedMessageEnvelope->getMessage()->getDeviceToken() . '" from the queue of Apns\Gateway with certificate "' . $this->getCertificate()->getDescription() . '"');
			}
			else
			{
				$this->logger->error('Failed retrieve message envelope for message #' . $errorMessage['identifier'] . ' that failed sending with statuscode #' . $errorMessage['status'] . ' from the queue of Apns\Gateway with certificate "' . $this->getCertificate()->getDescription() . '"');
			}

			// All messages that are send after the failed message should be send again
			$this->logger->info('Requeueing ' . ($this->lastMessageId - $errorMessage['identifier']) . ' messages that where send after the failed message to the queue of Apns\Gateway with certificate "' . $this->getCertificate()->getDescription() . '"');
			$lastMessageToResend = $this->lastMessageId;
			for ($messageId = $errorMessage['identifier'] + 1; $lastMessageToResend >= $messageId; $messageId++)
			{
				// Get the message envelope
				$messageEnvelope = $this->retrieveMessageEnvelope($messageId);

				// Check if it's send without errors
				if (null !== $messageEnvelope && $messageEnvelope->getStatus() == MessageEnvelope::STATUS_NOERRORS)
				{
					// Mark the message as failed due earlier error and requeue the message
					$retryMessageEnvelope = $this->queue( $messageEnvelope->getMessage() );
					$messageEnvelope->setStatus(MessageEnvelope::STATUS_EARLIERERROR, $retryMessageEnvelope);
					$this->logger->debug('Failed to send Apns\Message #' . $this->lastMessageId . ' "' . $messageEnvelope->getStatusDescription() . '" to device "' . $messageEnvelope->getMessage()->getDeviceToken() . '" on Apns\Gateway with certificate "' . $this->getCertificate()->getDescription() . '"');
				}
				else
				{
					$this->logger->warning('Could not requeue message #' . $this->lastMessageId . ' "Envelope already purged from envelope store" to the queue of Apns\Gateway with certificate "' . $this->getCertificate()->getDescription() . '"');
				}
			}

			// Reconnect and go on
			$this->connect();
		}
	}
786358
def checkResponse(self, ps, action):
        ''' 
        
        '''
        namespaceURI = self.wsAddressURI
        d = {namespaceURI:("MessageID","Action","To","From","RelatesTo")}
        typecodes = self._getWSAddressTypeCodes(**d)
        pyobjs = ps.ParseHeaderElements(typecodes)

        got_action = pyobjs.get((namespaceURI,"Action"))
        self._checkAction(action, got_action)

        From = pyobjs.get((namespaceURI,"From"))
        self._checkFrom(From)

        RelatesTo = pyobjs.get((namespaceURI,"RelatesTo"))
        self._checkRelatesTo(RelatesTo)

        To = pyobjs.get((namespaceURI,"To"))
        if To: self._checkReplyTo(To)
910295
def __check_response_for_fedex_error(self):
        

        if self.response.HighestSeverity == "FAILURE":
            for notification in self.response.Notifications:
                if notification.Severity == "FAILURE":
                    raise FedexFailure(notification.Code,
                                       notification.Message)
848036
def is_connection_error(e):
    
    return (isinstance(e, err.InterfaceError) and e.args[0] == "(0, '')") or\
        (isinstance(e, err.OperationalError) and e.args[0] in operation_error_codes.values())
1120974
def get_error(self, errstr):
        '''
        
        '''
        for line in errstr.split('\n'):
            if line.startswith('ssh:'):
                return line
            if line.startswith('Pseudo-terminal'):
                continue
            if 'to the list of known hosts.' in line:
                continue
            return line
        return errstr
981162
function checkErrors(error, response) {
        if (error) {
            return error instanceof Error ? error : new Error(error);
        }

        // Bamboo API enable plan returns 204 with empty response in case of success
        if ((response.statusCode !== 200) && (response.statusCode !== 204)) {
            return new Error("Unreachable endpoint! Response status code: " + response.statusCode);
        }

        return false;
    }
788595
def check_response(response):
    
    status_code = response.status_code

    if 100 < status_code < 299:
        return True

    elif status_code == 401 or status_code == 403:
        message = get_response_data(response)
        raise AuthError('Access Token Error, Received ' + str(status_code) +
                        ' from Outlook REST Endpoint with the message: {}'.format(message))

    elif status_code == 400:
        message = get_response_data(response)
        raise RequestError('The request made to the Outlook API was invalid. Received the following message: {}'.
                           format(message))
    else:
        message = get_response_data(response)
        raise APIError('Encountered an unknown error from the Outlook API: {}'.format(message))
1166531
def check_status(self):
        """"""
        logger.debug("Checking for a broker_url on django settings...")

        broker_url = getattr(settings, "BROKER_URL", None)

        logger.debug("Got %s as the broker_url. Connecting to rabbit...", broker_url)

        logger.debug("Attempting to connect to rabbit...")
        try:
            # conn is used as a context to release opened resources later
            with Connection(broker_url) as conn:
                conn.connect()  # exceptions may be raised upon calling connect
        except ConnectionRefusedError as e:
            self.add_error(ServiceUnavailable("Unable to connect to RabbitMQ: Connection was refused."), e)

        except AccessRefused as e:
            self.add_error(ServiceUnavailable("Unable to connect to RabbitMQ: Authentication error."), e)

        except IOError as e:
            self.add_error(ServiceUnavailable("IOError"), e)

        except BaseException as e:
            self.add_error(ServiceUnavailable("Unknown error"), e)
        else:
            logger.debug("Connection estabilished. RabbitMQ is healthy.")
960322
def _check_response_for_request_errors(self):
        
        if self.response.HighestSeverity == "ERROR":
            for notification in self.response.Notifications:  # pragma: no cover
                if notification.Severity == "ERROR":
                    if "Postal Code Not Found" in notification.Message:
                        raise FedexPostalCodeNotFound(notification.Code,
                                                      notification.Message)

                    elif "Invalid Postal Code Format" in self.response.Notifications:
                        raise FedexInvalidPostalCodeFormat(notification.Code,
                                                           notification.Message)
                    else:
                        raise FedexError(notification.Code,
                                         notification.Message)
626966
function TryPaperErrorStatus(response) {
  MessagingServiceStatus.call(this, 'trypaper');

  this.state.message = response.message;

  if (response.status_code == 400) this.state.code = this.StatusCodes.DATA_REJECTED;
  else if (response.status_code == 500) this.state.code = this.StatusCodes.SERVICE_DOWN;
  else this.state.code = this.StatusCodes.DEFAULT;
}
1129397
def _validate_apns_certificate(self, certfile):
		""""""

		try:
			with open(certfile, "r") as f:
				content = f.read()
				check_apns_certificate(content)
		except Exception as e:
			raise ImproperlyConfigured(
				"The APNS certificate file at %r is not readable: %s" % (certfile, e)
			)
490862
def check_response(self, resp):
        """"""
        if resp.status_code == 400:
            raise ApiException(json.loads(resp.content).get('message'))
        return resp
568886
def err_response(reqid, code, msg, data=None):
    
    err = { "code": code, "message": msg }
    if data:
        err["data"] = data
    return { "jsonrpc": "2.0", "id": reqid, "error": err }
978358
@Override
	public Response checkMessagingConnectionWithAgent(
			String applicationName,
			String scopedInstancePath,
			String message ) {

		this.logger.fine( "Request: check the connection with agent " + applicationName + " :: " + scopedInstancePath + ". message=" + message );
		final ManagedApplication ma = this.manager.applicationMngr().findManagedApplicationByName( applicationName );
		String lang = lang( this.manager );

		Response response;
		int pingResult;
		final Instance instance;

		if( ma == null )
			response = handleError( Status.NOT_FOUND, new RestError( REST_INEXISTING, application( applicationName )), lang ).build();
		else if(( instance = InstanceHelpers.findInstanceByPath( ma.getApplication(), scopedInstancePath )) == null )
			response = handleError( Status.NOT_FOUND, new RestError( REST_INEXISTING, instance( scopedInstancePath ), application( applicationName )), lang ).build();
		else if(( pingResult = this.manager.debugMngr().pingAgent( ma, instance, message )) == 1 )
			response = handleError( Status.BAD_REQUEST, new RestError( REST_DEBUG_AGENT_KO ), lang ).build();
		else if( pingResult == 2 )
			response = handleError( Status.INTERNAL_SERVER_ERROR, new RestError( REST_MESSAGING_ERROR ), lang ).build();
		else
			response = handleError( Status.OK, new RestError( REST_DEBUG_AGENT_KO, name( "PING" ), value( message )), lang ).build();

		return response;
	}
1358909
def get_error(response):
    """"""

    errors = {
        400: BadRequestError,
        401: UnauthorizedError,
        403: AccessDeniedError,
        404: NotFoundError,
        429: RateLimitExceededError,
        500: ServerError,
        502: BadGatewayError,
        503: ServiceUnavailableError
    }

    error_class = HTTPError
    if response.status_code in errors:
        error_class = errors[response.status_code]

    return error_class(response)
964540
def _check_connection(self):
        
        # check if connection is expired
        reset = False
        if self._force_recon:
            self.logger.warning(
                "[%s:%s] Error communicating with socket, resetting "
                "connection",
                self.fn or self.host, self.port)
            reset = True

        elif self.heartbeat_controller.is_expired():
            self.logger.warning(
                "[%s:%s] Heartbeat timeout, resetting connection",
                self.fn or self.host, self.port)
            reset = True

        if reset:
            for channel in self._open_channels:
                self.disconnect_channel(channel)
            self._report_connection_status(
                ConnectionStatus(CONNECTION_STATUS_LOST,
                                 NetworkAddress(self.host, self.port)))
            try:
                self.initialize_connection()
            except ChromecastConnectionError:
                self.stop.set()
            return False
        return True
1354549
function shouldReconnect(err) {
  // exclude all programming errors
  return (!(err instanceof TypeError) &&
          !(err instanceof InvalidArgumentError) &&
          !(err instanceof NotPermittedError) &&
          !(err instanceof ReplacedError) &&
          !(err instanceof StoppedError) &&
          !(err instanceof SubscribedError) &&
          !(err instanceof UnsubscribedError)
  );
}