Handles parsing response structure and translating API Exceptions
5670
def meta_request(func):
    
    def inner(self, resource, *args, **kwargs):
        serialize_response = kwargs.pop('serialize', True)
        try:
            resp = func(self, resource, *args, **kwargs)
        except ApiException as e:
            raise api_exception(e)
        if serialize_response:
            return serialize(resource, resp)
        return resp

    return inner
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)
321054
static public void captureReponseErrors(Object response, String errorMessage) throws Exception {
		if( null == response ) {
			throw new Exception("Capturing errors from null response");
		}
		if( false == (response instanceof JSONObject) ) {
			// Not an error
			return;
		}
		JSONObject obj = (JSONObject)response;
		if( JSONSupport.containsKey(obj,"error") ) {
			String serverMessage;
			try {
				serverMessage = obj.getString("error");
			} catch (Exception e) {
				serverMessage = "Unable to parse error response";
			}
			
			if( null == errorMessage ) {
				errorMessage = "Error returned by database: ";
			}
			throw new Exception(errorMessage+serverMessage);
		}
	}
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)
        )
378385
def _catch_index_error(self, response):
        
        code, headers, raw_data = response
        if not raw_data:
            return
        data = json.loads(raw_data)
        if not data or not data.get('errors'):
            return
        try:
            error_dict = data['items'][0]['index']
            message = error_dict['error']
        except (KeyError, IndexError):
            return
        raise exception_response(400, detail=message)
105213
function parseResponse(cb) {
  return function parse(err, response, body) {
    // TODO Handel the errors
    cb(err, JSON.parse(body))
  }
}
38873
function responseErrorBuilder(err, res) {
  if (res && res.body && _.isObject(res.body) && res.body.error) {
    // pass through error obj from API
    return res.body;
  } else {
    // build custom error
    return {
      error: {
        code: err.status || CL_CONSTANTS.RES_UNKNOWN,
        message: (res ? res.text : null) || err.toString(),
      }
    };
  }
}
1149082
def _parse_content(response):
    """"""
    if response.status_code != 200:
        raise ApiError(f'unknown error: {response.content.decode()}')
    result = json.loads(response.content)
    if not result['ok']:
        raise ApiError(f'{result["error"]}: {result.get("detail")}')
    return result
302331
def exception_translation(func):
    
    @wraps(func)
    def decorator(*arg, **kwargs):
        try:
            return func(*arg, **kwargs)
        except InvalidOperationException, e:
            return Response(status=status.HTTP_412_PRECONDITION_FAILED, data={'detail': e.message}, headers={'Content-Type': 'application/json'})
    return decorator
839223
def parse_response(self, resp):
        
        p, u = self.getparser()

        if hasattr(resp,'text'):
            # modern requests will do this for us
            text = resp.text # this is unicode(py2)/str(py3)
        else:

            encoding = requests.utils.get_encoding_from_headers(resp.headers)
            if encoding is None:
                encoding='utf-8' # FIXME: what to do here?

            if sys.version_info[0]==2:
                text = unicode(resp.content, encoding, errors='replace')
            else:
                assert sys.version_info[0]==3
                text = str(resp.content, encoding, errors='replace')
        p.feed(text)
        p.close()
        return u.close()
972088
protected void skipResponseStatusExceptionParsing(String json) throws ResponseErrorJsonParsingException {
    // If this is not an object, it's not an error response.
    if (!json.startsWith("{")) {
      throw new ResponseErrorJsonParsingException();
    }

    int subStrEnd = Math.min(50, json.length());
    if (!json.substring(0, subStrEnd).contains("\"error\"")) {
      throw new ResponseErrorJsonParsingException();
    }
  }
1078035
function convertApiError(err) {
	if (err.error && err.error.response && err.error.response.text) {
		const obj = JSON.parse(err.error.response.text);
		if (obj.errors && obj.errors.length) {
			err = { message: obj.errors[0].message, error:err.error };
		}
	}
	return err;
}
965417
def __parseForException(self, http_error):
        
        data = http_error.body
        try:
            if isinstance(data, str):
                data = cjson.decode(data)
        except:
            raise http_error

        if isinstance(data, dict) and 'exception' in data:# re-raise with more details
            raise HTTPError(http_error.url, data['exception'], data['message'], http_error.header, http_error.body)

        raise http_error
10424
async def handle_json_response(responses):
        
        json_data = {}
        if responses.status != 200:
            err_msg = HttpProcessingError(code=responses.status,
                                          message=await responses.json())
            logging.error("Wallabag: aiohttp error {err_msg}".format(
                err_msg=err_msg))
        else:
            try:
                json_data = responses.json()
            except ClientResponseError as e:
                # sometimes json_data does not return any json() without
                # any error. This is due to the grabbing URL which "rejects"
                # the URL
                logging.error("Wallabag: aiohttp error {code} {message}"
                              .format(code=e.code, message=e.message))
        return await json_data
510917
def prepare_exception(obj, messages=None, response=None, verbs=None):
    
    # pylint:disable=too-many-branches
    verbs = set(verbs or [])
    known_options = ['method+url']
    if messages is None:
        messages = []
    if isinstance(messages, (text_type, str)):
        messages = [messages]
    assert isinstance(messages, list)
    assert not verbs.difference(known_options)

    data = None
    # a boolean from a failed response is False, though error messages in json should be decoded
    if response is not None and 'json' in response.headers.get('Content-Type', '') and response.text:
        data = json.loads(response.text)
        if data:
            data_0 = data[0]
            if 'errorCode' in data_0:
                subreq = ''
                if 'referenceId' in data_0:
                    subreq = " (in subrequest {!r})".format(data_0['referenceId'])
                messages = [data_0['errorCode'] + subreq] + messages
            if data_0.get('fields'):
                messages.append('FIELDS: {}'.format(data_0['fields']))
            if len(data) > 1:
                messages.append('MORE_ERRORS ({})'.format(len(data)))
    if 'method+url' in verbs:
        method = response.request.method
        url = response.request.url
        if len(url) > 100:
            url = url[:100] + '...'
        data_info = ''
        if (method in ('POST', 'PATCH') and
                (not response.request.body or 'json' not in response.request.headers['content-type'])):
            data_info = ' (without json request data)'
        messages.append('in {} "{}"{}'.format(method, url, data_info))
    separ = '\n    '
    if not PY3:
        messages = [x if isinstance(x, str) else x.encode('utf-8') for x in messages]
    messages = [x.replace('\n', separ) for x in messages]
    message = separ.join(messages)
    if obj:
        obj.data = data
        obj.response = response
        obj.verbs = verbs
    return message
60352
def handle_response(response)
      return super(response)
    rescue ActiveResource::ClientError => exc
      begin
        # ugly code to insert the error_message into response
        error_message = "#{format.decode response.body}"
        if not error_message.nil? or error_message == ""
          exc.response.instance_eval do ||
            @message = error_message
          end
        end
      ensure
        raise exc
      end
    end
984987
def parse_response(resp)
      body = JSON.parse(resp.body)
      if body['error']
        raise Apilayer::Error.new(
          body['error']['info'],
          body['error']['code']
        )
      else
        body
      end
    end