Ensures the request is always sent and that the response code was checked.
543455
private function doDestruct()
    {
        if ($this->initializer && null === $this->info['error']) {
            ($this->initializer)($this);
            $this->initializer = null;
            $this->checkStatusCode();
        }
    }
787663
async def Check(self, stream):
        """"""
        request = await stream.recv_message()
        checks = self._checks.get(request.service)
        if checks is None:
            await stream.send_trailing_metadata(status=Status.NOT_FOUND)
        elif len(checks) == 0:
            await stream.send_message(HealthCheckResponse(
                status=HealthCheckResponse.SERVING,
            ))
        else:
            for check in checks:
                await check.__check__()
            await stream.send_message(HealthCheckResponse(
                status=_status(checks),
            ))
500653
def declare_response(self, code='200', **kwargs):
        """"""  # noqa: E501
        self['responses'][str(code)] = self._new_operation(**kwargs)
1267579
def after_start_check(self):
        
        try:
            if self.url.scheme == 'http':
                conn = HTTPConnection(self.host, self.port)
            elif self.url.scheme == 'https':
                ssl_context = None
                if not self.verify_tls:
                    ssl_context = ssl._create_unverified_context()
                conn = HTTPSConnection(
                    self.host,
                    self.port,
                    context=ssl_context,
                )
            else:
                raise ValueError(f'Unsupported URL scheme: "{self.url.scheme}"')

            self._send_request(conn)
            response = conn.getresponse()
            status = str(response.status)

            if not self._validate_response(response):
                return False

            if status == self.status or self.status_re.match(status):
                conn.close()
                return True

        except (HTTPException, socket.timeout, socket.error) as ex:
            log.debug('Executor process not healthy yet', command=self.command, error=ex)
            time.sleep(.05)
            return False

        return False
482883
public static void checkStatus(CloseableHttpResponse httpResponse, final int httpStatus)
      throws SDKException {

    if (httpResponse.getStatusLine().getStatusCode() != httpStatus) {
      log.error(
          "Status expected: "
              + httpStatus
              + " obtained: "
              + httpResponse.getStatusLine().getStatusCode());
      log.error("httpresponse: " + httpResponse.toString());
      String body;
      try {
        body = EntityUtils.toString(httpResponse.getEntity());
      } catch (IOException e) {
        e.printStackTrace();
        throw new SDKException(
            "Status is " + httpResponse.getStatusLine().getStatusCode(),
            new StackTraceElement[0],
            "could not provide reason because: " + e.getMessage());
      }
      log.error("Body: " + body);
      throw new SDKException(
          "Status is " + httpResponse.getStatusLine().getStatusCode(),
          new StackTraceElement[0],
          body);
    }
  }
213291
def ensure_success!(response)
      return if response.is_a? Net::HTTPSuccess

      message = "#{response.code} - #{response.message}"
      message += "\n#{response.body}" if response.body.present?

      raise Crapi::BadHttpResponseError, message
    end
1158419
function sendResponse(code, message, statusCode) {
    /*jshint validthis:true*/
    var res = this;
    var data;
    var result;

    if (!res) {
      throw new Error('You called `error()`, detatched send from the response object');
    }

    code = code || 'UKN';
    message = message || (errors[code] && errors[code].message) || 'Unknown error occurred';
    statusCode = statusCode || (errors[code] && errors[code].statusCode) || '200';
    data = { code: code, message: message };

    res.setHeader('Content-Type', 'application/json');
    //res.statusCode = statusCode;
    if (code && 'object' === typeof code) {
      if (code.error) {
        code = code.error;
      }
      if (/message/.test(JSON.stringify(code))) {
        // '{}' !== JSON.stringify(code)
        data = code;
      } else {
        data = { type: code.type, name: code.name, message: code.message || code.toString() };
      }
    }

    result = JSON.stringify({ error: data }, null, '  ');
    res.end(result);
  }
1295616
@SuppressWarnings("unused")
    final void handleStatusCode(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) {
        StringBuilder stringBuilder = state.stringBuilder;
        while (buffer.hasRemaining()) {
            final char next = (char) buffer.get();
            if (next == ' ' || next == '\t') {
                builder.setStatusCode(Integer.parseInt(stringBuilder.toString()));
                state.state = ResponseParseState.REASON_PHRASE;
                state.stringBuilder.setLength(0);
                state.parseState = 0;
                state.pos = 0;
                state.nextHeader = null;
                return;
            } else {
                stringBuilder.append(next);
            }
        }
    }
1114573
def handleStatus(self, version, code, message):
        ""
        proxy.ProxyClient.handleStatus(self, version, code, message)
        # client.Response is currently just a container for needed data
        self._response = client.Response(version, code, message, {}, None)
1255720
function sendStatus(code, res){
	try{
		if (httpCodeMapping) {
			code = mapHttpStatusCode(code);
		}
		addStrictTransportHeaders(res);
		setResponseNoCache(res);
		return res.sendStatus(code);
	}catch(err){
		logger.error(res.req.originalUrl , err.message);
		throw err;
	}
}
1121628
def check_status_code(response, codes=None):
    
    codes = codes or [httplib.OK]
    checker = (
        codes
        if callable(codes)
        else lambda resp: resp.status_code in codes
    )
    if not checker(response):
        raise exceptions.ApiError(response, response.json())
1251718
def checkResponse(request):
        '''
        
        '''

        # Check the status code of the returned request
        if str(request.status_code)[0] not in ['2', '3']:
            w = str(request.text).split('\\r')[0][2:]
            raise InvalidRequest(w)
        return
573334
public static boolean hasResponseBody(String requestMethod, int responseCode) {
        return requestMethod != Request.Method.HEAD
                && !(100 <= responseCode && responseCode < HttpURLConnection.HTTP_OK)
                && responseCode != HttpURLConnection.HTTP_NO_CONTENT
                && responseCode != HttpURLConnection.HTTP_RESET
                && responseCode != HttpURLConnection.HTTP_NOT_MODIFIED;
    }
553304
function status(url, code, mod) {
      return this.get(url, mod).then(req => req.statusCode === code);
    }
1353251
def _handle_response(self, transaction):
        
        code = transaction.response.code
        utils.check_code(code)
        """
        VALID response:
        change the current cache value by switching the option set with the one provided
        also resets the timestamp
        if the request etag is different from the response, send the cached response
        """
        if code == Codes.VALID.number:
            logger.debug("received VALID")
            self.cache.validate(transaction.request, transaction.response)
            if transaction.request.etag != transaction.response.etag:
                element = self.cache.search_response(transaction.request)
                transaction.response = element.cached_response
            return transaction

        """
        CHANGED, CREATED or DELETED response:
        mark the requested resource as not fresh
        """
        if code == Codes.CHANGED.number or code == Codes.CREATED.number or code == Codes.DELETED.number:
            target = self.cache.search_related(transaction.request)
            if target is not None:
                for element in target:
                    self.cache.mark(element)
            return transaction

        """
        any other response code can be cached normally
        """
        self.cache.cache_add(transaction.request, transaction.response)
        return transaction
204346
def safe_request(
    url,
    method=None,
    params=None,
    data=None,
    json=None,
    headers=None,
    allow_redirects=False,
    timeout=30,
    verify_ssl=True,
):
    """"""

    session = requests.Session()

    kwargs = {}

    if json:
        kwargs['json'] = json
        if not headers:
            headers = {}
        headers.setdefault('Content-Type', 'application/json')

    if data:
        kwargs['data'] = data

    if params:
        kwargs['params'] = params

    if headers:
        kwargs['headers'] = headers

    if method is None:
        method = 'POST' if (data or json) else 'GET'

    response = session.request(
        method=method,
        url=url,
        allow_redirects=allow_redirects,
        timeout=timeout,
        verify=verify_ssl,
        **kwargs
    )

    return response
958880
def send_response(self, code, message=None, size='-'):
        
        # pylint: disable-msg=W0221
        if self._to_log or LOG.isEnabledFor(logging.DEBUG):
            self.log_request(code, size)

        if message is None:
            if code in self.responses:
                message = self.responses[code][0]
            else:
                message = ''

        if self.request_version != 'HTTP/0.9':
            self.wfile.write("%s %d %s\r\n" %
                             ("HTTP/1.1", code, message))
        self.send_header('Server', self.version_string())
        self.send_header('Date', self.date_time_string())