Handles response and error codes from remote service.
178836
def handle_response(response)
      case response.code.to_i
        when 301,302
          raise "Redirect"
        when 200...400
          response
        when 400
          raise "Bad Request"
        when 401
          raise "Unauthorized Access"
        when 403
          raise "Forbidden Access"
        when 404
          raise "Rescoure not found"
        when 405
          raise "Method not allowed"
        when 409
          raise RequestError.new("Rescource conflict")
        when 422
          raise RequestError.new("Resource invalid")
        when 401...500
          raise "Client error"
        when 500...600
          raise RequestError.new("Server error")
        else
          raise "Unknown response: #{response.code.to_i}"
      end
    end
951404
def handle_api_error(resp):
    """"""
    content = yield resp.json()

    headers = HeaderWrapper(resp.headers)

    try:
        err = content['error']
    except (KeyError, TypeError):
        raise error.APIError(
            "Invalid response object from API: %r (HTTP response code "
            "was %d)" % (content, resp.code),
            resp, resp.code, content, headers)

    if resp.code in [400, 404]:
        raise error.InvalidRequestError(
            err.get('message'), err.get('param'),
            resp, resp.code, content, headers)
    elif resp.code == 401:
        raise error.AuthenticationError(
            err.get('message'),
            resp, resp.code, content, headers)
    elif resp.code == 402:
        raise error.CardError(
            err.get('message'), err.get('param'), err.get('code'),
            content, resp.code, resp, headers)
    else:
        raise error.APIError(
            err.get('message'), content, resp.code, resp, headers)
177225
def _handle_response(self, msg_id, result=None, error=None):
        """"""
        request_future = self._server_request_futures.pop(msg_id, None)

        if not request_future:
            log.warn("Received response to unknown message id %s", msg_id)
            return

        if error is not None:
            log.debug("Received error response to message %s: %s", msg_id, error)
            request_future.set_exception(JsonRpcException.from_dict(error))

        log.debug("Received result for message %s: %s", msg_id, result)
        request_future.set_result(result)
860521
def _handle_http_errors(response):
    
    code = response.status_code
    if 200 <= code < 400:
        return response
    elif code in (403, 404):
        raise {403: _ObjectPermissionError,
               404: _ObjectNotFoundError}[code](response.reason)
    response.raise_for_status()
255367
function handlePreResponseError(server) {
        server.ext('onPreResponse', function (request, reply) {
            var response = request.response;
            var originalResponse = response;
            var msg;

            // No error, keep going with the reply as normal
            if (!response.isBoom) { reply.continue(); return; }

            // we need to convert to AppError if it is not already
            if (!(response instanceof AppError)) {
                msg = response.message || (response + '');

                // if legit 404 be sure to use that code (happens with not found in /dist on local)
                if (msg.indexOf('404:') >= 0 ||
                    (response.output && response.output.payload &&
                    response.output.payload.statusCode === 404)) {

                    response = new AppError({
                        code: 'not_found',
                        msg: 'The resource ' + request.url.path + ' was not found'
                    });
                }
                else {
                    msg = response.message || (response + '');
                    if (response.data) { msg += ' : ' + response.data; }

                    log.info(msg);

                    response = new AppError({
                        code: response.code || 'api_error',
                        msg: msg,
                        err: response
                    });
                }
            }

            var code = response.code || 'unknown_error';
            var err = errorDecoder[code] || errorDecoder['unknown_error'];
            var url = request.path;

            if (err.httpErrorCode === 404) {
                trackingService.pageNotFound({
                    caller: request.caller,
                    url: routeHelper.getBaseUrl(request.app.name) + url
                });
            }
            else {
                log.error(request.method + ' ' + url + ' (' + err.friendlyMessage + ')',
                    { err: originalResponse }   );
            }

            //TODO: this hack sucks, but needed quick way to display error page; do better!
            if (pancakes.getContainer() === 'webserver') {

                // hack fix for issue when error on trust site
                if (request.app && request.app.name === 'trust') {
                    reply().redirect(routeHelper.getBaseUrl('contact') + '?notify=loginFailure');
                }
                // else show error pages
                else {
                    var errUrl = err.httpErrorCode === 404 ? '/error404' : '/error500';
                    pancakes.processRoute({ request: request, reply: reply, urlOverride: errUrl, returnCode: err.httpErrorCode });
                }
            }
            else {
                reply(Boom.create(err.httpErrorCode, err.friendlyMessage));
            }
        });
    }
867664
def handle_exception(error):
    """"""
    try:
        if _get_acceptable_response_type() == JSON:
            response = jsonify(error.to_dict())
            response.status_code = error.code
            return response
        else:
            return error.abort()
    except InvalidAPIUsage:
        # In addition to the original exception, we don't support the content
        # type in the request's 'Accept' header, which is a more important
        # error, so return that instead of what was originally raised.
        response = jsonify(error.to_dict())
        response.status_code = 415
        return response
534452
function processResponse(err, res, cb){
  if(!err) {
    if(Array.isArray(res.body)){
      res.body.forEach(function (body) {
        castRecordDateFields(body);
      });
    } else if (_.isObject(res.body)) {
      castRecordDateFields(res.body);
    }
  }
  cb();
}
689055
def error_handling(cls, fn):
        """"""
        def wrapper(*args, **kwargs):
            try:
                result = fn(*args, **kwargs)
                return result
            except InvalidRequestError as e:
                write_exception(e)

                if hasattr(e, 'request'):
                    write_error_message('request {0}'.format(repr(e.request)))
                if hasattr(e, 'response'):
                    write_error_message('response {0}'.format(repr(e.response)))

                raise e
        return wrapper
135497
def error_response(
    error_type="Internal server error",
    error_text="",
    status=400,
    participant=None,
    simple=False,
    request_data="",
):
    """"""
    last_exception = sys.exc_info()
    if last_exception[0]:
        db.logger.error(
            "Failure for request: {!r}".format(dict(request.args)),
            exc_info=last_exception,
        )

    data = {"status": "error"}

    if simple:
        data["message"] = error_text
    else:
        data["html"] = (
            error_page(
                error_text=error_text,
                error_type=error_type,
                participant=participant,
                request_data=request_data,
            )
            .get_data()
            .decode("utf-8")
        )
    return Response(dumps(data), status=status, mimetype="application/json")
662196
def handle_error(self, msgtype, msgid, error):
        """"""
        self._proxy.error(msgid, error)
326191
def handle_error(self, error=None):
        """"""
        if _debug: TCPServer._debug("handle_error %r", error)

        # core does not take parameters
        asyncore.dispatcher.handle_error(self)
747233
def handle_response(self, msgtype, msgid, response):
        """"""
        self._proxy.response(msgid, response)
776345
def errorhandle(self, resp):            
        """"""
        if self.format == 'json':
            parsed = xmltodict.parse(resp)
            errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN]
            # Create list of errors if more than one error response is given
            if type(errors) is list and len(errors) > 1:
                messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors])
            else:
                overlimit = any('transaction limit' in msg.lower() for msg in errors.values())
                if overlimit:
                    raise APILimitExceeded("This API key has used up its daily quota of calls.")
                else:    
                    messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()])    
        elif self.format == 'xml':
            import xml.etree.ElementTree as ET
            errors = ET.fromstring(resp).findall(self.ERROR_TOKEN)
            messages = ", ".join(err.find('msg').text for err in errors)
        else:
            raise ValueError("Invalid API response format specified: {}." % self.format)        
        
        raise BustimeError("API returned: {}".format(messages))
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)
912295
def _handle_response(self, response):
        
        if response.status_code == requests.codes.ok or response.status_code == requests.codes.created:
            try:
                return response.json()
            except ValueError:
                return response
        else:
            return self._handle_failed_response(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 }
1249353
def _handle_error_response(self, bucket_name=None):
        
        if not self._response.data:
            self._set_error_response_without_body(bucket_name)
        else:
            self._set_error_response_with_body(bucket_name)