For failed instance/handle lookups, older-clients expect an response object with noops
that include `rejected promise APIs`
@param service
@param handle
@returns {Object}
356906
function addLegacyAPI(service, handle) {
    var falseFn = function() {
      return false;
    };
    var rejectFn = function() {
      return $q.when($mdUtil.supplant(errorMsg, [handle || ""]));
    };

    return angular.extend({
      isLockedOpen: falseFn,
      isOpen: falseFn,
      toggle: rejectFn,
      open: rejectFn,
      close: rejectFn,
      onClose: angular.noop,
      then: function(callback) {
        return waitForInstance(handle).then(callback || angular.noop);
      }
    }, service);
  }
773506
private Object getServiceHandler(IScope scope, String serviceName) {
        // get application scope handler first
        Object service = scope.getHandler();
        if (serviceName == null || serviceName.equals("")) {
            // no service requested, return application scope handler
            log.trace("No service requested, return application scope handler: {}", service);
            return service;
        }
        // search service resolver that knows about service name
        for (IServiceResolver resolver : serviceResolvers) {
            service = resolver.resolveService(scope, serviceName);
            if (service != null) {
                return service;
            }
        }
        // requested service does not exist
        return null;
    }
659762
function handle(err, results) {
      if (err) {
        errors.push(err);
      }

      // add all responses to the array
      (Array.isArray(results) ? results : [results]).forEach(function each(value) {
        if (value && memcached.namespace.length) {
          var ns_key = Object.keys(value)[0]
            , newvalue = {};

          newvalue[ns_key.replace(memcached.namespace, '')] = value[ns_key];
          Utils.merge(responses, newvalue);
        } else {
          Utils.merge(responses, value);
        }
      });

      if (!--calls){
          callback(errors.length ? errors : undefined, responses);
      }
    }
472760
function (promise){
    		promise.success = function (fn) {
	            promise.then(fn);
	            return promise;
	        };

	        promise.error = function (fn) {
	            promise.then(null, fn);
	            return promise;
	        };
    	}
681738
function Injector(obj){
  var services = {};
  var get = name => {
    if(!(name in services)){
      const err = new Error(`[injector] service "${name}" not found`);
      return Promise.reject(err);
    }
    return services[name];
  };
  if(typeof obj === 'object')
    services = obj;
  if(typeof obj === 'function')
    get = obj;
  function resolve(name) {
    let service = get(name);
    if(typeof service === 'function')
      service = invoke(service);
    return service;
  };
  function invoke(fn, that){
    return Promise
    .all(getParameterNames(fn).map(resolve))
    .then(params => fn.apply(that, params));
  }
  return invoke;
}
1310337
function handleError(error, ignoreError) {
    appStore.setLoading(false)
    let reason

    if (error.response) {
        reason = handleResponseError(error)
    } else if (error.status >= 200 && error.status < 300) {
        reason = handleServiceError(error)
    } else {
        reason = handleRequestError(error)
    }

    if (ignoreError !== true) {
        appStore.setError(reason)
    }

    return Promise.reject(reason)
}
426038
function getHandler (method, getArgs, trans, domain = 'feathers') {
  return function (req, res, next) {
    res.setHeader('Allow', Object.values(allowedMethods).join(','));

    let params = Object.assign({}, req.params || {});
    delete params.service;
    delete params.id;
    delete params.subresources;
    delete params[0];

    req.feathers = { provider: 'rest' };
    // Grab the service parameters. Use req.feathers and set the query to req.query

    let query = req.query || {};
    let headers = fp.dissoc('cookie', req.headers || {});
    let cookies = req.cookies || {};

    params = Object.assign({ query, headers }, params, req.feathers);

    // Transfer the received file
    if (req.file) {
      params.file = req.file;
    }

    // method override
    if ((method === 'update' || method === 'patch')
      && params.query.$method 
      && params.query.$method.toLowerCase() === 'patch') {
      method = 'patch'
      delete params.query.$method
    }

    // Run the getArgs callback, if available, for additional parameters
    const [service, ...args] = getArgs(req, res, next);

    debug(`REST handler calling service \'${service}\'`, {
      cmd: method,
      path: req.path,
      //args: args,
      //params: params,
      //feathers: req.feathers
    });

    // The service success callback which sets res.data or calls next() with the error
    const callback = function (err, data) {
      debug(`${service}.${method} response:`, err || {
        status: data && data.status,
        size: data && JSON.stringify(data).length
      });
      if (err) return next(err.cause || err);

      res.data = data;

      if (!data) {
        debug(`No content returned for '${req.url}'`);
        res.status(statusCodes.noContent);
      } else if (method === 'create') {
        res.status(statusCodes.created);
      }

      return next();
    };

    trans.act({
      topic: `${domain}.${service}`,
      cmd: method,
      path: req.path,
      args: args,
      params: params,
      feathers: req.feathers
    }, callback);
  };
}
682720
function handleResponseError(error) {
    console.error('handleResponseError', error)
    let reason
    const status = error.response.status

    if (status === 404) {
        reason = wrap('接口不存在')
    } else {
        reason = wrap(defaultErrorMessage)
    }

    return reason
}
1332749
function () {
  /**
   * Renders an error view from a template and sends data to client
   * @param  {Object}   opts Configurable options (see periodicjs.core.responder for more details)
   * @param {string|Object} opts.err Error details for response
   * @param {Object} opts.req Express request object
   * @param {Object} opts.res Express response object
   * @param  {Function} [callback]   Optional callback function
   * @return {Object}      If callback is not defined returns a Promise which resolves after response has been sent
   */
  let fn = function handleDocumentQueryErrorResponse (opts = {}, callback) {
    let { err, req, res } = opts;
    if (opts.use_warning) this.protocol.warn(req, res, { err });
    else this.protocol.error(req, res, { err });
    if (req.query.format === 'json' || req.params.ext === 'json' || path.extname(req.originalUrl) === '.json' || req.is('json') || req.params.callback || req.is('application/json')) {
      return this.protocol.respond(req, res, { err });
    }
    else if (typeof callback === 'function') {
      return this.responder.error(err)
        .then(result => callback(null, result))
        .catch(callback);
    }
    else if (req.redirecturl) {
      req.redirectpath = (!req.redirectpath && req.redirecturl) ? req.redirecturl : req.redirectpath;
      return this.protocol.redirect(req, res);
    }
    else {
      return this._utility_responder.error(err, {})
        .then(result => {
          return this.protocol.respond(req, res, { responder_override: result });
        }, err => {
          return this.protocol.exception(req, res, { err });
        });
    }
  };
  let message = 'CoreController.handleDocumentQueryErrorResponse: Use CoreController.responder.error with an HTML adapter or CoreController._utility_responder.error instead';
  return wrapWithDeprecationWarning.call(this, fn, message);
}
1057132
function(handle) {
        if (!isValidID(handle)) return null;

        var i, j, instance;
        for (i = 0, j = instances.length; i < j; i++) {
          instance = instances[i];
          if (instance.$$mdHandle === handle) {
            return instance;
          }
        }
        return null;
      }
965397
function(request) {
    return new Promise((resolve, reject) => {
      this._start()
          .uri('/api/system/audit-log/search')
          .setJSONBody(request)
          .post()
          .go(this._responseHandler(resolve, reject));
    });
  }
924120
function handleError(res) {
  return function (err) {
    if (err.status && err.name !== 'NotFoundError') {
      // If we're in this block, the error has a defined `status` property and
      // the error should be directed out immediately
      sendDefaultResponseForCode(err.status, err.message, res);
    } else if (err.name === 'NotFoundError' ||
      err.message.indexOf('ENOENT') !== -1 ||
      err.message.indexOf('not found') !== -1) {
      notFound(err, res);
      // if the word "client" is ever in a message, it should be for the client.  We enforce that here.
    } else if (err.message.indexOf('Client') !== -1) {
      clientError(err, res);
    } else {
      serverError(err, res);
    }
  };
}
732971
function handleServiceError(error) {
    console.error('handleServiceError', error)
    // data 为服务器端返回的报文
    const data = error.data || {}
    const code = +data.code

    // 401 token失效
    if (code === 401) {
        // 当前系统使用的是 HashRouter，所以这里取hash部分
        const href = window.location.hash
        const loginPath = '/#/user/login'

        // 清空token
        appStore.setToken(null)

        // 如果当前不是在登录页，即跳转到登录
        if (href.indexOf(loginPath.substring(1)) === -1) {
            window.location = loginPath
        }
        // 这里返回值会被外层捕获，并且设值为appStore.error
        // 为避免在跳转页面后，弹出错误提示，这里需要返回null
        return null
    }

    // 其它业务异常，由外边处理
    return data
}
883160
function Request_handleError(response) {
        var request, code, that = this;

        if (this.isRendered) {
            // we have multiple recursion in parse for catching
            return false;
        }
        // log error request
        logger.error('Request:', {
            url: this.url,
            status: this.statusCode,
            id: this.id,
            isRendered: this.isRendered,
            content_type: this.getHeader('content-type'),
            message: response
        });

        if (response instanceof Error) {
            response = error.silentHttpError(500, {}, 'SlientHttpError: mvcjs error is not thrown', response);
        }
        // get error code from message
        code = getErrorCode(response);
        // set status codes
        this.setStatusCode(code);
        // stop current chain!!!
        this.stopPromiseChain();

        response += '\n';
        response += 'ROUTE:' + core.inspect(this._getRouteInfo());

        if (!this.isERROR && !!router.getErrorRoute()) {
            // return new request
            this.isRendered = true;

            request = new Request({
                request: this.request,
                response: this.response,
                isForwarded: true,
                body: this.body,
                isERROR: true
            }, router.createUrl(router.getErrorRoute()));
            // pass exception response over parsed url query as query parameter
            // assign to exception
            request.parsedUrl.query.exception = response;
            // set status codes for new request
            request.setStatusCode(code);
            // return parsed request
            return request.parse();
        } else {
            this.addHeader('Content-Type', 'text/plain');
            return response;
        }
    }
856450
async function start(service) {
  return new Promise((resolve) => {
    const snapshotsDir = path.join(__dirname, '../../test/services/', service.name, 'snapshots');
    const app = yakbak(service.defaultUrl, {
      dirname: snapshotsDir,
      hash: customHash
    });
    const proxy = http.createServer(app).listen(service.port, () => {
      console.log(`Yakbak server listening on port ${service.port}. Proxy for ${service.defaultUrl}`);
    });

    resolve(proxy);
  });
}
1173351
function apiService() {

    'use strict';

    /*jshint validthis: true */

    var service = this;

    /**
     * trace errors to console
     * @var {Boolean}
     */
    this.trace = false;

    /**
     * HTTP status for service
     * will be used only by REST service
     * @var {Number}
     */
    this.httpstatus = 200;

    /**
     * Path used in getService
     * defined withing the function app.getService
     * @var {String}
     */
    this.path = null;


    /**
     * Service outcome
     * contain success boolean
     * a list of alert messages
     * errfor: errors associated to fields
     */
    this.outcome = {
        success: true,
        alert: [],
        errfor: {}
    };

    this.Q = require('q');

    /**
     * Defered service result
     */
    this.deferred = this.Q.defer();

    /**
     * Services instances must implement
     * this method to resolve or reject the service promise
     *
     * @param {Object} params
     *
     * @return {Promise}
     */
    this.getResultPromise = function(params) {
        console.log('Not implemented');

        return this.deferred.promise;
    };

    /**
     * Set application
     * @param {Object} app
     */
    this.setApp = function(app) {
        service.app = app;
    };


    /**
     * Add alert to service
     * @param {string} type   One of boostrap alert types (danger|success|info)
     * @param {String|Error} err  Error message or object
     */
    this.addAlert = function(type, err) {

        var alert = { type: type };

        if (err instanceof Error) {
            alert.message = err.name+' : '+err.message;
            alert.stack = err.stack;

        } else if (typeof err === 'string') {
            alert.message = err;
        } else {
            console.error(err);
            throw new Error('Wrong error type, must be a string or Error, got '+(typeof err));
        }

        service.outcome.alert.push(alert);
    };


    /**
     * Get an error object from a mixed value
     * @param   {String|Error} err
     * @returns {Error}
     */
    this.getError = function(err) {
        if (err instanceof Error) {
            return err;
        }

        return new Error(err);
    };



    /**
     *  Reject the service promise with an forbidden status
     * The server understood the request, but is refusing to fulfill it.
     * Authorization will not help and the request SHOULD NOT be repeated.
     * If the request method was not HEAD and the server wishes to make public
     * why the request has not been fulfilled, it SHOULD describe the reason for
     * the refusal in the entity. If the server does not wish to make this
     * information available to the client, the status code 404 (Not Found)
     * can be used instead.
     * @param {String|Error} err
     */
    this.forbidden = function(err) {
        service.httpstatus = 403;
        service.outcome.success = false;
        service.addAlert('danger', err);

        service.deferred.reject(service.getError(err));
    };


    /**
     * Reject the service promise with an error status
     * The HTTP server encountered an unexpected condition which prevented
     * it from fulfilling the request.
     * For example this error can be caused by a serveur misconfiguration,
     * or a resource exhausted or denied to the server on the host machine.
     *
     * @param {String|Error} err
     */
    this.error = function(err) {

        if (err.name === 'ValidationError') {
            return service.handleMongoError(err); // 400
        }

        service.httpstatus = 500;
        service.outcome.success = false;
        service.addAlert('danger', err);

        service.deferred.reject(service.getError(err));
    };


    /**
     * Ouput a 404 error
     * with an outcome message
     *
     * @param {String|Error} err
     */
    this.notFound = function(err) {
        service.httpstatus = 404;
        service.outcome.success = false;

        service.addAlert('danger', err);

        service.deferred.reject(service.getError(err));
    };


    /**
     * Ouput a 410 error
     * with an outcome message
     *
     * @param {String|Error} err
     */
    this.gone = function(err) {
        service.httpstatus = 410;
        service.outcome.success = false;

        service.addAlert('danger', err);

        service.deferred.reject(service.getError(err));
    };


    /**
     * Set a success message into outcome
     * @param {String} message
     */
    this.success = function(message) {

        service.addAlert('success', message);

    };


    /**
     * output document and $outcome with a sucess message
     *
     * @param {Document} document           Mongoose document
     * @param {String} message              message for outcome
     */
    this.resolveSuccess = function(document, message) {

        service.outcome.success = true;
        service.success(message);

        var output;
        if (document.toObject) {
            output = document.toObject();
        } else {
            output = document;
        }
        output.$outcome = service.outcome;

        service.deferred.resolve(output);
    };


    /**
     * Get a document using the sibling get service
     * @param {String} param all parameters or document ID to get, this will set the 'id' param in the parameters given to GET service
     * @return {Promise} promise resolve to an object but without the $outcome property
     */
    this.get = function(param) {
        if (null === service.path) {
            throw new Error('The path need to be defined in the app.getService function');
        }

        var path = service.path.split('/');
        delete path[path.length-1];

        if (typeof param !== 'object' || param.constructor.name === 'ObjectID') {
            param = { id: param };
        }

        return service.app.getService(path.join('/')+'/get')
        .getResultPromise(param)
        .then(function(serviceObject) {
            delete serviceObject.$outcome;
            return serviceObject;
        });
    };


    /**
     * output document from the sibling get service and $outcome with a sucess message
     * @param {String} param       savedDocument ID or parameters
     * @param {String} message  message for outcome
     */
    this.resolveSuccessGet = function(param, message) {

        this.get(param).then(function(document) {
            service.resolveSuccess(document, message);
        })
        .catch(service.error);
    };


    /**
     * emit exception if parameter contain a mongoose error
     *
     * @param {Error|null} err - a mongoose error or no error
     * @param {Boolean} trace   set to false to disable console.trace of the error
     *
     * @return {Boolean}
     */
    this.handleMongoError = function(err) {
        if (err) {

            if (true === service.trace) {
                console.trace(err);
            }

            service.httpstatus = 400; // Bad Request

            if (err.errors) {
              for(var field in err.errors) {
                  var e = err.errors[field];
                  service.outcome.errfor[field] = e.type;
                  service.outcome.alert.push({ type:'danger' ,message: e.message});
              }
            }

            service.outcome.alert.push({ type:'danger' ,message: err.message});
            service.outcome.success = false;

            service.deferred.reject(new Error(err.message));
            return false;
        }

        return true;
    };



    /**
     * @return {Boolean}
     */
    this.hasErrors = function() {

        if (Object.keys(service.outcome.errfor).length !== 0) {
            return true;
        }

        for(var i=0; i<service.outcome.alert.length; i++) {
            if (service.outcome.alert[i].type === 'danger') {
                return true;
            }
        }

        return false;
    };


}
416305
function ServerClientStream(app){
    var StreamHandler;
    app.use(function(req, res, next){
      if(req.originalUrl == '/promise-pipe-connector' && req.method=='POST'){
        var message = req.body;
        message._response = res;
        StreamHandler(message)
      } else {
        return next();
      }
    });
    return {
      send: function(message){
        if(!message._response) throw Error("no response defined");
        var res = message._response;
        message._response = undefined;
        res.json(message);
      },
      listen: function(handler){
        StreamHandler = handler;
      }
    }
  }