Parse body of request and raise HTTP errors in case of problems
430058
def parse_request(request, input_schema, raw):
    """"""

    request.json = {}
    if not raw:
        body = yield from request.read()
        if body:
            try:
                request.json = json.loads(body.decode('utf-8'))
            except ValueError as e:
                request.json = {"malformed_json": body.decode('utf-8')}
                raise aiohttp.web.HTTPBadRequest(text="Invalid JSON {}".format(e))

    # Parse the query string
    if len(request.query_string) > 0:
        for (k, v) in urllib.parse.parse_qs(request.query_string).items():
            request.json[k] = v[0]

    if input_schema:
        try:
            jsonschema.validate(request.json, input_schema)
        except jsonschema.ValidationError as e:
            log.error("Invalid input query. JSON schema error: {}".format(e.message))
            raise aiohttp.web.HTTPBadRequest(text="Invalid JSON: {} in schema: {}".format(
                e.message,
                json.dumps(e.schema)))

    return request
410536
def raw(self):
        
        try:
            return urlopen(str(self.url))
        except HTTPError as error:
            try:
                # parse error body as json and use message property as error message
                parsed = self._parsejson(error)
                exc = RequestError(parsed['message'])
                exc.__cause__ = None
                raise exc
            except ValueError:
                # when error body is not valid json, error might be caused by server
                exc = StatbankError()
                exc.__cause__ = None
                raise exc
659308
def _validate_response(url, response):
    """"""
    if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK,
                                  GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS]:
        error_detail = ('Request to URL %s failed with response code: %s' %
                        (url, response['status']))
        raise GooglePlacesError(error_detail)
987045
def parse_request(api_secret, reqbody, dec_func=False):
    
    try:
        if type(reqbody) == type(dict):
            return self.parse_form_request(reqbody)
            
        if callable(dec_func):
            req_msg = json.loads(dec_func(reqbody))
        else:
            req_msg = json.loads(reqbody)
    except Exception as err:
        raise ParseError(u"parse params error")

    if not check_sign(api_secret, req_msg):
        raise SignError(u"message sign error")

    return Storage(req_msg)
379100
def _parse_req(self, req):
		'''
		'''
		if DEBUG:
			if req.status_code != requests.codes.ok:
				print(("code: {}".format(req.status_code)))
				print(("response {}".format(req.json())))
				print(("req headers {}".format(req.request.headers)))
				print(("req body {}".format(req.request.body)))
1337128
def __check_http_err(self, status_code):
        """"""
        if status_code == 403:
            raise exceptions.APIAuthenticationError(self.api_key)
        elif status_code == 503:
            raise exceptions.APITimeoutError()
        else:
            return False
211795
def errors
      if response.decoded_body
        response.decoded_body['errors'] ||
          response.decoded_body[:errors] ||
          response.decoded_body
      else
        response.body
      end
    end
1061001
def _parse_request(header_data, ignore_bad_cookies=False):
    
    cookies_dict = {}
    for line in Definitions.EOL.split(header_data.strip()):
        matches = Definitions.COOKIE_RE.finditer(line)
        matches = [item for item in matches]
        for match in matches:
            invalid = match.group('invalid')
            if invalid:
                if not ignore_bad_cookies:
                    raise InvalidCookieError(data=invalid)
                _report_invalid_cookie(invalid)
                continue
            name = match.group('name')
            values = cookies_dict.get(name)
            value = match.group('value').strip('"')
            if values:
                values.append(value)
            else:
                cookies_dict[name] = [value]
        if not matches:
            if not ignore_bad_cookies:
                raise InvalidCookieError(data=line)
            _report_invalid_cookie(line)
    return cookies_dict
1340358
def check_response(response)
      if response.status >= 400
        parsed_body = JSON.parse(response.body)
        raise Errors::GenericError.new(parsed_body['code'], parsed_body['message'])
      end
    end
1326823
function onError( error ) {
		debug( 'Error encountered while querying endpoint: %s', error.message );
		if ( error instanceof Error ) {
			err = {
				'status': 500,
				'message': 'Request error: ' + error.message
			};
			return clbk( err );
		}
		return clbk( error, res, body );
	}
1273893
function parseBody(req, limit, callback) {
  const body = [];

  function handleData(data) {
    body.push(data);

    /**
    Stop collecting data and call the callback with an error if request exceeds limit.
    Calling function should close the connection.
    */
    if (Buffer.concat(body).length > limit) {
      req.removeListener('data', handleData);
      req.removeListener('end', handleEnd);

      const error = new Error();
      error.httpCode = 413;
      error.message = http.STATUS_CODES[413];

      callback(error);
    }
  }

  function handleEnd() {
    const type = req.headers['content-type'];

    if (type === 'application/x-www-form-urlencoded') {
      callback(null, querystring.parse(Buffer.concat(body).toString()));

    } else if (type === 'application/json') {
      callback(null, JSON.parse(Buffer.concat(body).toString()));

    } else {
      callback(null, Buffer.concat(body).toString());
    }
  }

  req.on('data', handleData);
  req.on('end', handleEnd);
}
75454
function toDefaultErrorResponseBody(error) {
  const json = error && error.toJSON();
  if (json) {
    if (json.httpStatus) {
      delete json.httpStatus; // don't really need `httpStatus` inside `body` too, since have it in response as `statusCode`
    }
    if (json.headers) {
      delete json.headers; // don't want error's `headers` inside `body`, since have more comprehensive `headers` in response
    }
  }
  return json;
}
551831
def parse(self, method, endpoint, body):
        '''  '''
        if isinstance(body, dict):  # request body was already parsed
            return body
        if endpoint == 'list':
            return self.parse_list(body)

        return self.parse_detail(body)
532832
def raise_http_error(cls, response):
        """"""
        response_xml = response.read()
        logging.getLogger('recurly.http.response').debug(response_xml)
        exc_class = recurly.errors.error_class_for_http_status(response.status)
        raise exc_class(response_xml)
413702
def handle_error(response, body)
      unless [200, 201].include?(response.status)
        raise Passfort::Errors::RequestError.new([], response)
      end

      errors = body["errors"].is_a?(Array) ? body["errors"] : [body["errors"]]

      handle_response_error(errors, response) if errors.any?
    end
446146
function parse(method, req, res, options) {
    return new Promise(function(resolve, reject) {
        BodyParser[method](options)(req, res, function(err) {
            if (err) {
                return reject(err);
            }

            return resolve();
        });
    });
}
39179
function parseBodyParam (req, res, next) {
  let params = getParams(req);

  params.some((param) => {
    if (param.in === "body") {
      util.debug('    Parsing the "%s" body parameter', param.name);

      if (_.isPlainObject(req.body) && _.isEmpty(req.body)) {
        if (param.type === "string" || (param.schema && param.schema.type === "string")) {
          // Convert {} to ""
          req.body = "";
        }
        else {
          // Convert {} to undefined
          req.body = undefined;
        }
      }

      // Parse the body
      req.body = parseParameter(param, req.body, param.schema);

      // There can only be one "body" parameter, so skip the rest
      return true;
    }
  });

  // If there are no body/formData parameters, then reset `req.body` to undefined
  if (params.length > 0) {
    let hasBody = params.some((param) => {
      return param.in === "body" || param.in === "formData";
    });

    if (!hasBody) {
      req.body = undefined;
    }
  }

  next();
}