Helper function to extract the JSON body out of a response OR throw an exception.

        :param res: the response from a request
        :return: the JSON body OR throws an exception
189923
def _get_response_json(self, res):
        

        try:
            error = res.json()
        except ValueError:
            error = {
                "message": "The API did not respond with JSON, but: {0}".format(res.text[:1000]),
                "error_code": "{0}".format(res.status_code)
            }
        return error
1281892
def get(self, res, cls, default = None):
        

        try:
            return self[(res, cls)]
        except KeyError:
            return default
10815
def _serialize(self):
        

        # Do something appropriate if the response object is unbound
        if self._defcode is None:
            raise exceptions.UnboundResponse()

        # Build the response
        resp = self.response_class(request=self.req, status=self.code,
                                   headerlist=self._headers.items())

        # Do we have a body?
        if self.result:
            resp.content_type = self.content_type
            resp.body = self.serializer(self.result)

        # Return the response
        return resp
855841
def get_body(self, environ=None):
        """"""
        body = dict(
            status=self.code,
            message=self.description,
        )

        errors = self.get_errors()
        if self.errors:
            body['errors'] = errors

        return json.dumps(body)
104603
function getJSON (response) {
  return response.json().then((body) => {
    if (body.status !== 'ok') {
      throw error(response, body.status, body.data[0])
    }
    return body
  })
}
888409
def process_response(self, response: requests.models.Response) -> dict:
        
        try:
            output = response.json()
        except json.JSONDecodeError: # Server is having a bad day and crashed.
            raise self.BadResponseError(
                'Json not returned with status code [' + str(response.status_code) + ']')

        if response.status_code == 400:
            return output

        if response.status_code not in [200, 201]: # Safety catch.
            raise self.BadResponseError(
                str(output) + ': with status code [' + str(response.status_code) +
                '] and params:' + str(output))

        return output['data']
330883
def process_response(response)
        raise ArgumentError, 'response is null' if response.nil?

        if block_given?
          yield
        end


        # return code
        if 401 == response.code
          raise UnauthorizedError, compose_error_message(response)
        elsif 500 == response.code
          raise ServerError, compose_error_message(response)
        elsif 2 != (response.code / 100)
          raise OrientdbError, "unexpected return code, code=#{response.code}, body=#{compose_error_message(response)}"
        end

        content_type = response.headers[:content_type] if connection_library == :restclient
        content_type = response.headers['Content-Type'] if connection_library == :excon
        content_type ||= 'text/plain'

        rslt = case
          when content_type.start_with?('text/plain')
            response.body
          when content_type.start_with?('application/x-gzip')
            response.body
          when content_type.start_with?('application/json')
            ::JSON.parse(response.body)
          else
            raise OrientdbError, "unsuported content type: #{content_type}"
          end

        rslt
      end
278979
def from_response(response, url):
    
    # noinspection PyBroadException
    try:
        data = response.json()
        if not isinstance(data, dict):
            return from_status(
                response.status_code, response.text,
                extra=dict(url=url, response=response.text)
            )

        code = data.get('code', response.status_code)
        if code in HTTP_STATUS_CODES:
            return HTTP_STATUS_CODES[code](**ErrorSchema().load(data))
        else:
            return Error(**ErrorSchema().load(data))
    except Exception:
        return from_status(
            response.status_code, response.text,
            extra=dict(url=url, response=response.text)
        )
817133
def _request_process_json(self, response):
        
        data = []
        try:
            if self._api_branch == 'bulk':
                response_data = self._request_bulk(response)
            else:
                response_data = response.json()

            if self._request_entity is None:
                data = response_data
                status = 'Success'
            elif self._api_branch == 'bulk':
                data, status = self._request_process_json_bulk(response_data)
            elif response_data.get('data') is None:
                data, status = self._request_process_json_status(response_data)
            elif response_data.get('status') == 'Success':
                data, status = self._request_process_json_standard(response_data)

                # setup pagination
                if self._result_count is None:
                    self._result_count = response_data.get('data', {}).get('resultCount')
            else:
                self.tcex.log.error('Failed Request: {}'.format(response.text))
                status = 'Failure'
        except KeyError as e:
            # TODO: Remove try/except block
            status = 'Failure'
            msg = u'Error: Invalid key {}. [{}] '.format(e, self.request_entity)
            self.tcex.log.error(msg)
        except ValueError as e:
            # TODO: Remove try/except block
            status = 'Failure'
            msg = u'Error: ({})'.format(e)
            self.tcex.log.error(msg)

        return data, status
1216215
def parse_response(response):
    
    if response.headers.get('Content-Type', JSON_TYPE).startswith(JSON_TYPE):
        return ResponseObject(json.loads(response.body))
    else:
        return response.body
1161150
def render_exception_js(self, exception):
        

        from .http import JsonResponse

        response = {}
        response["error"] = exception.error
        response["error_description"] = exception.reason

        return JsonResponse(response, status=getattr(exception, 'code', 400))
221061
def body_as_json(self, encoding='UTF-8'):
        
        data_str = self.body_as_str(encoding=encoding)
        try:
            return json.loads(data_str)
        except Exception as e:
            raise TypeError("Event data is not compatible with JSON type: {}".format(e))
124383
def extract_response(raw_response):
    
    data = urlread(raw_response)

    if is_success_response(raw_response):
        return data
    elif is_failure_response(raw_response):
        raise RemoteExecuteError(data)
    elif is_invalid_response(raw_response):
        raise InvalidResponseError(data)
    else:
        raise UnknownStatusError(data)
769878
def wo_resp(self, resp):
        
        if self._data is not None:
            resp['res'] = self.to_str(self._data)

        return self.wo_json(resp)
1143963
def json(self):
        

        if six.PY3:
            return json.loads(self.body.decode(self.charset))
        else:
            return json.loads(self.body)
157716
def _handle_response(self, url, res, suppress_empty=True):
        
        self._last_response = res
        result = {}
        if res.status_code in (200, 201, 202):
            try:
                result = res.json()
            except Exception as e:  # json might be invalid, or store might be down
                e.message += " (_handle_response failed to decode JSON: " + str(res.content) + ")"
                raise  # TODO better exception
        elif res.status_code == 204 and not suppress_empty:
            raise EmptyResponseWarning("%d %s @ %s: %s" % (res.status_code, res.reason, url, res.content), res)
        elif res.status_code >= 500:
            raise ServerException("%d %s @ %s: %s" % (res.status_code, res.reason, url, res.content), res)
        elif res.status_code == 429:
            raise RateLimitingException("%d %s @ %s: %s" % (res.status_code, res.reason, url, res.content), res)
        elif res.status_code >= 400:
            raise ClientRequestException("%d %s @ %s: %s" % (res.status_code, res.reason, url, res.content), res)
        elif res.status_code >= 300:
            raise RedirectionException("%d %s @ %s: %s" % (res.status_code, res.reason, url, res.content), res)
        return result
512301
def _error_handling(self, res):
        

        # making the error handling generic so if an status_code starting with 2 doesn't exist, we raise the error
        if res.status_code // 100 != 2:
            error = self._get_response_json(res)
            raise exceptions.KeenApiError(error)