Convert a response payload or exception to a status code and payload.

    This function will convert an Exception raised by an RPC implementation
    to the corresponding status code.
547735
def pack_rpc_response(response=None, exception=None):
    

    if response is None:
        response = bytes()

    if exception is None:
        status = (1 << 6)
        if len(response) > 0:
            status |= (1 << 7)
    elif isinstance(exception, (RPCInvalidIDError, RPCNotFoundError)):
        status = 2
    elif isinstance(exception, BusyRPCResponse):
        status = 0
    elif isinstance(exception, TileNotFoundError):
        status = 0xFF
    elif isinstance(exception, RPCErrorCode):
        status = (1 << 6) | (exception.params['code'] & ((1 << 6) - 1))
    else:
        status = 3

    return status, response
347769
def _handle_api_error(self, error):
        
        status_code = error.response.status_code
        message = error.message

        if 403 == status_code:
            raise NewRelicInvalidApiKeyException(message)
        elif 404 == status_code:
            raise NewRelicUnknownApplicationException(message)
        elif 422 == status_code:
            raise NewRelicInvalidParameterException(message)
        else:
            raise NewRelicApiException(message)
725861
def _handle_response(self, response):
        
        if not str(response.status_code).startswith('2'):
            raise build_api_error(response)
        return response
86696
async def _handle_exception(self, e, sock):
        
        if isinstance(e, (RemoteProtocolError, AssertionError)):
            await sock.close()
            raise BadHttpResponse('Invalid HTTP response from server.') from e

        if isinstance(e, Exception):
            await sock.close()
            raise e
623010
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception {
		sc_stats[] resources = new sc_stats[1];
		sc_response result = (sc_response) service.get_payload_formatter().string_to_resource(sc_response.class, response);
		if(result.errorcode != 0) {
			if (result.errorcode == 444) {
				service.clear_session();
			}
			if(result.severity != null)
			{
				if (result.severity.equals("ERROR"))
					throw new nitro_exception(result.message,result.errorcode);
			}
			else
			{
				throw new nitro_exception(result.message,result.errorcode);
			}
		}
		resources[0] = result.sc;
		return resources;
	}
1355454
def _decode_response(response):
    
    status_code = response.status_code

    message = "Status code " + str(status_code)
    try:
      message = CraftAIClient._parse_body(response)["message"]
    except (CraftAiInternalError, KeyError, TypeError):
      pass

    if status_code in [200, 201, 204, 207]:
      return CraftAIClient._parse_body(response)
    else:
      raise CraftAIClient._get_error_from_status(status_code, message)
    return None
850875
def throw_if_parsable(resp):
    
    e = None
    try:
        e = parse_response(resp)
    except:
        # Error occurred during parsing the response. We ignore it and delegate
        # the situation to caller to handle.
        LOG.debug(utils.stringify_expt())

    if e is not None:
        raise e

    if resp.status_code == 404:
        raise NoSuchObject('No such object.')
    else:
        text = resp.text if six.PY3 else resp.content
        if text:
            raise ODPSError(text, code=str(resp.status_code))
        else:
            raise ODPSError(str(resp.status_code))
1297492
private void sendOpsResponse(VoltTable[] results, JSONObject obj, byte payloadType) throws Exception
    {
        long requestId = obj.getLong("requestId");
        long returnAddress = obj.getLong("returnAddress");
        // Send a response with no data since the stats is not supported or not yet available
        if (results == null) {
            ByteBuffer responseBuffer = ByteBuffer.allocate(8);
            responseBuffer.putLong(requestId);
            byte responseBytes[] = CompressionService.compressBytes(responseBuffer.array());
            BinaryPayloadMessage bpm = new BinaryPayloadMessage( new byte[] {payloadType}, responseBytes);
            m_mailbox.send(returnAddress, bpm);
            return;
        }

        ByteBuffer[] bufs = new ByteBuffer[results.length];
        int statbytes = 0;
        for (int i = 0; i < results.length; i++) {
            bufs[i] = results[i].getBuffer();
            bufs[i].position(0);
            statbytes += bufs[i].remaining();
        }

        ByteBuffer responseBuffer = ByteBuffer.allocate(
                8 + // requestId
                4 * results.length + // length prefix for each stats table
                + statbytes);
        responseBuffer.putLong(requestId);
        for (ByteBuffer buf : bufs) {
            responseBuffer.putInt(buf.remaining());
            responseBuffer.put(buf);
        }
        byte responseBytes[] = CompressionService.compressBytes(responseBuffer.array());

        BinaryPayloadMessage bpm = new BinaryPayloadMessage( new byte[] {payloadType}, responseBytes);
        m_mailbox.send(returnAddress, bpm);
    }
75494
def decode_response(status: int, headers: MutableMapping, body: bytes) -> dict:
    
    data = decode_body(headers, body)
    raise_for_status(status, headers, data)
    raise_for_api_error(headers, data)

    return data
639249
def parse(cls, payload):
        
        try:
            method, args, ref = payload
        except Exception as exception:
            raise RequestParseError(exception)
        else:
            return method, args, ref
626107
def __process_gprest_response(self, r=None, restType='GET'):
        
        if r is None:
            logging.info('No response for REST '+restType+' request')
            return None

        httpStatus = r.status_code
        logging.info('HTTP status code: %s', httpStatus)

        if httpStatus == requests.codes.ok or \
            httpStatus == requests.codes.created:
            jsonR = r.json()
            if jsonR:
                statusStr = 'REST response status: %s' % \
                    jsonR.get(self.__RESPONSE_STATUS_KEY)
                msgStr = 'REST response message: %s' % \
                    jsonR.get(self.__RESPONSE_MESSAGE_KEY)
                logging.info(statusStr)
                logging.info(msgStr)
                return jsonR
            else:
                logging.warning('Unable to parse JSON body.')
                logging.warning(r.text)
                return None
        logging.warning('Invalid HTTP status code.')
        logging.warning(r.text)
        return r.json()
555424
def render_to_json(response, request=None, **kwargs):
    
    # determine the status code
    if hasattr(response, 'status_code'):
        status_code = response.status_code
    elif issubclass(type(response), Http404):
        status_code = 404
    elif issubclass(type(response), Exception):
        status_code = 500
        logger.exception(str(response), extra={'request': request})
        
        if settings.DEBUG:
            import sys
            reporter = ExceptionReporter(None, *sys.exc_info())
            text = reporter.get_traceback_text()
            response = HttpResponseServerError(text, content_type='text/plain')
        else:
            response = HttpResponseServerError("An error occured while processing an AJAX request.", content_type='text/plain')
    else:
        status_code = 200

    # creating main structure
    data = {
        'status': status_code,
        'statusText': REASON_PHRASES.get(status_code, 'UNKNOWN STATUS CODE'),
        'content': response
    }

    return JSONResponse(data, **kwargs)
884260
def response_error(response):
    ""
    response = response.split(' ')
    error_code = response[0]
    if error_code not in EXCEPTION_CLASSES:
        error_code = 'ERR'
    response = ' '.join(response[1:])
    return EXCEPTION_CLASSES[error_code](response)
1073408
def check_status_code(response, codes=None):
    
    codes = codes or [200]
    if response.status_code not in codes:
        raise StatusCodeError(response.status_code)
884840
def get_response(self, **kwargs):
        
        return Response(
            json.dumps({"error": self.message}),  # pylint: disable=exception-message-attribute
            status_code=self.status_code,
            content_type="application/json",
            charset="utf-8",
            **kwargs
        )
1358350
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception {
		ssl_stats[] resources = new ssl_stats[1];
		ssl_response result = (ssl_response) service.get_payload_formatter().string_to_resource(ssl_response.class, response);
		if(result.errorcode != 0) {
			if (result.errorcode == 444) {
				service.clear_session();
			}
			if(result.severity != null)
			{
				if (result.severity.equals("ERROR"))
					throw new nitro_exception(result.message,result.errorcode);
			}
			else
			{
				throw new nitro_exception(result.message,result.errorcode);
			}
		}
		resources[0] = result.ssl;
		return resources;
	}
967885
def result_or_error(response):
    
    data = response.json()
    result = data.get('result')
    if result is not None:
        return result
    raise exceptions.ApiError(response, data)