Return JSON decoded response from API call. Handle errors when bad response encountered.
341198
def clef_error_check(func_to_decorate):
    """"""
    def wrapper(*args, **kwargs):
        try:
            response = func_to_decorate(*args, **kwargs)
        except requests.exceptions.RequestException:
            raise ConnectionError(
                'Clef encountered a network connectivity problem. Are you sure you are connected to the Internet?'
            )
        else:
            raise_right_error(response)
        return response.json() # decode json
    return wrapper
1364675
def _handle_error_response(response_body):
    "
    try:
        error_data = json.loads(response_body)
        error_details = '{}: {}'.format(
            error_data['error'],
            error_data.get('error_description'))
    # If no details could be extracted, use the response data.
    except (KeyError, ValueError):
        error_details = response_body

    raise exceptions.RefreshError(
        error_details, response_body)
811648
def _get_json_response(self, resp):
        '''  '''
        if resp is not None and resp.text is not None:
            try:
                text = resp.text.strip('\n')
                if len(text) > 0:
                    return json.loads(text)
            except ValueError as e:
                if self.debug:
                    print("Could not decode JSON response: \"%s\"" % resp.text)
                raise e
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
1236961
def json_response(self, status=200, data={}, headers={}):
        '''
          
        '''
        mimetype = 'application/json'

        header_dict = {}
        for k, v in headers.items():
            header_dict[k] = v

        return Response(
            json.dumps(data),
            status=status,
            mimetype=mimetype,
            headers=header_dict)
842599
def _process_json_response(self, response):
        '''  '''

        json_response = self._get_json_response(response)
        
        if self.response_callback is not None:
            json_response = self.response_callback(json_response)
            response._content = json.dumps(json_response)

        self.http_status_code = response.status_code
        self._check_error(response, json_response)
        self._check_warnings(json_response)

        return json_response
447233
def handle_errors(resp):
    """"""
    if resp.status_code == 400:
        raise ApiException(json.loads(resp.content).get('message'))
    return resp
1361416
def handle_exception(error):
        
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
        return response
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)
        )
767963
def response_json(self, status, response, content_type='application/json', encoding='utf-8', headers=None, jsonp=None):
        

        encoder = JSONEncoder(
            check_circular=self.app.validate_output,
            allow_nan=False,
            sort_keys=True,
            indent=2 if self.app.pretty_output else None,
            separators=(',', ': ') if self.app.pretty_output else (',', ':')
        )
        content = encoder.encode(response)
        if jsonp:
            content_list = [jsonp.encode(encoding), b'(', content.encode(encoding), b');']
        else:
            content_list = [content.encode(encoding)]
        return self.response(status, content_type, content_list, headers=headers)
470590
def parse_response(self, response):
        
        status = response.status_code
        if response.ok:
            data = response.json()
            return HttpResponse(ok=response.ok, status=status, errors=None, data=data)
        else:
            try:
                errors = response.json()
            except ValueError:
                errors = response.content
            return HttpResponse(ok=response.ok, status=status, errors=errors, data=None)
302765
def _catch_nonjson_streamresponse(rawresponse):
        
        # attempt to load response for return.
        try:
            response = json.loads(rawresponse)
        except (ValueError, TypeError):
            if rawresponse:
                response = {
                    '_error': [
                        {
                            'message': 'Response not in JSON format.',
                            'data': rawresponse,
                        }
                    ]
                }
            else:
                # in case of null response, return empty dict.
                response = {}

        return response
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 }
1171069
def __call(self, uri, params=None, method="get"):
        
        try:
            resp = self.__get_response(uri, params, method, False)
            rjson = resp.json(**self.json_options)
            assert resp.ok
        except AssertionError:
            msg = "OCode-{}: {}".format(resp.status_code, rjson["message"])
            raise BadRequest(msg)
        except Exception as e:
            msg = "Bad response: {}".format(e)
            log.error(msg, exc_info=True)
            raise BadRequest(msg)
        else:
            return rjson
59166
function checkResponseForErrors(res) {
    let { statusCode, body, headers } = res;

    if (statusCode >= 400) {
        return { error: true, body };
    }

    // API key is invalid
    if ((body.error) && (body.error === 'Unauthorized')) {
        return { error: true, body };
    }

    // response is not json
    if (headers['content-type'] !== 'application/json; charset=utf-8') {
        return { error: true, body: { error: 'JSON expected' } };
    }

    return { error: false, body };
}
865864
def process_json_response(self, response):
        """"""

        response_json = response.json()

        # handle errors
        code_key = "code"
        if code_key in response_json and response_json[code_key] != constants.HTTP_CODE_OK:
            code = response_json[code_key]

            message = response_json
            if "message" in response_json:
                message = response_json["message"]
            elif "code_description" in response_json:
                message = response_json["code_description"]

            if code == constants.HTTP_FORBIDDEN:
                raise housecanary.exceptions.UnauthorizedException(code, message)
            if code == constants.HTTP_TOO_MANY_REQUESTS:
                raise housecanary.exceptions.RateLimitException(code, message, response)
            else:
                raise housecanary.exceptions.RequestException(code, message)

        request_url = response.request.url

        endpoint_name = self._parse_endpoint_name_from_url(request_url)

        return Response.create(endpoint_name, response_json, response)
1039652
def handle_response(defopts, res)
      raise NetError.new(res.body)  unless res.code == '200'

      json = Yajl::Parser.parse(res.body)
      RegApi2.got_response(json)

      raise ApiError.from_json(json)  if json['result'] == 'error'

      res_contract = RegApi2::ResultContract.new(defopts)
      res_contract.handle_result(json)
    end