Tries to always return an expressDeliver exception
@param  {any} err
@param  {Array<ExceptionPool>} pools
@return {Exception}
193217
function normalizeError(err,pools){
    if (!(err instanceof Error)){
        err = new Error(err)
    }
    if (!err._isException){

        //Iterate over exceptionPools finding error match
        for(let i=0;i<pools.length;i++){
            let exception = pools[i]._convert(err)
            if (exception) return exception
        }
    }
    return err
}
533866
function sendErrorResponse(err, callback = undefined, returnData = undefined) {
  let error;
  if (err instanceof Error) {
    error = err;
  } else {
    error = new Error(err);
  }

  if (callback) {
    callback(error, returnData);
  } else {
    throw error;
  }
}
169145
function onError(err) {
    const ctx = this.$ctx;
    const cn = npm.utils.getSafeConnection(ctx.cn);
    npm.events.error(ctx.options, err, {cn, dc: ctx.dc});
    ctx.disconnect(err);
    if (ctx.cnOptions && typeof ctx.cnOptions.onLost === 'function' && !ctx.notified) {
        try {
            ctx.cnOptions.onLost.call(this, err, {
                cn,
                dc: ctx.dc,
                start: ctx.start,
                client: this
            });
        } catch (e) {
            npm.con.error(e && e.stack || e);
        }
        ctx.notified = true;
    }
}
1069531
private Connection<CL> getConnectionForTokenOnRackNoFallback(BaseOperation<CL, ?> op, Long token, String rack, int duration, TimeUnit unit, RetryPolicy retry)
            throws NoAvailableHostsException, PoolExhaustedException, PoolTimeoutException, PoolOfflineException {
        DynoConnectException lastEx = null;

        // find the selector for that rack,
		HostSelectionStrategy<CL> selector = findSelectorForRack(rack);
		// get the host using that selector
		HostConnectionPool<CL>  hostPool = selector.getPoolForToken(token);

        if (hostPool != null) {
            try {
                // Note that if a PoolExhaustedException is thrown it is caught by the calling
                // ConnectionPoolImpl#executeXXX() method
                return hostPool.borrowConnection(duration, unit);
            } catch (PoolTimeoutException pte) {
                lastEx = pte;
                cpMonitor.incOperationFailure(null, pte);
            }
        }

        if (lastEx == null) {
            throw new PoolOfflineException(hostPool == null ? null : hostPool.getHost(), "host pool is offline and we are forcing no fallback");
        } else {
            throw lastEx;
        }
    }
285244
function errorSerializer (err) {
  if (!err || !err.stack) return err
  const obj = {
    message: err.message,
    name: err.name,
    code: err.code,
    stack: getErrorStack(err)
  }
  return obj
}
910722
function(err, req, res) {

  console.log('handle error:');
  console.dir(err);

  // uri error
  if (err instanceof URIError) {
    return res.status(404).render('errors/404');
  }

  logger.error(req.method + ' ' + getURL(req) + ' : ' + err);
  logger.error(err.stack);

  if (!res._headerSent) {
    // show error
    if (config.showerrstack) {
      //
      const stacktrace = [
        '<h1>', req.originalUrl, '</h1>',
        '<pre>', err.stack, '</pre>'
      ].join('');
      res.status(500).send(stacktrace);
    } else {
      res.status(500).render('errors/500');
    }
  }

  if (config.mailcrashto) {
    mailer.send('crash', {
      to:       config.mailcrashto,
      subject:  [ config.appname, 'Crash:', err ].join(' '),
      body:     formatMessage(req, err)
    })
  }
}
1066842
function PromisePool(opts) {
    this._opts = {
        // Configuration options
        name:               opts.name || 'pool',
        idleTimeoutMillis:  opts.idleTimeoutMillis || 30000,
        reapInterval:       opts.reapIntervalMillis || 1000,
        drainCheckInterval: opts.drainCheckIntervalMillis || 100,
        refreshIdle:        ('refreshIdle' in opts) ? opts.refreshIdle : true,
        returnToHead:       opts.returnToHead || false,
        max:                parseInt(opts.max, 10),
        min:                parseInt(opts.min, 10),

        // Client management methods.
        create:     opts.create,
        destroy:    opts.destroy,
        validate:   opts.validate || function(){ return true; },
        onRelease:  opts.onRelease
    };

    this._availableObjects = [];
    this._waitingClients = new PriorityQueue(opts.priorityRange || 1);
    this._count = 0;
    this._removeIdleScheduled = false;
    this._removeIdleTimer = null;
    this._draining = false;

    // Prepare a logger function.
    if (opts.log instanceof Function) {
        this._log = opts.log;
    }
    else if (opts.log) {
        this._log = _logger.bind(this);
    }
    else {
        this._log = function(){};
    }

    // Clean up some of the inputs.
    this._validate = opts.validate || function(){ return true; };
    this._opts.max = Math.max(isNaN(this._opts.max) ? 1 : this._opts.max, 1);
    this._opts.min = Math.min(isNaN(this._opts.min) ? 0 : this._opts.min, this._opts.max-1);

    // Finally, ensure a minimum number of connections right out of the gate.
    _ensureMinimum.call(this);
}
258018
function errHandler(err) {
    process.stderr.write(chalk.red('Model generation failed!') + '\n');

    switch (err.code) {
      default:
        case 'PARSE_FAIL':
        if (!quiet) {
          process.stderr.write('\n' + err.stack + '\n');
        }
      break;

      case 'ENOENT':
          if (!quiet) {
            process.stderr.write('\n' + err.stack.replace('ENOENT, lstat ', 'unable to find ') + '\n');
          }
        break;
    }
    callback(err);
  }
175022
function run(pool, idx, executionFunction) {
  var p = Promise.resolve()
    .then(executionFunction)
    .then(function() {
      delete pool.promises[idx];
      var next = pool.queue.pop();
      if (next) {
        pool.execute(next);
      }
    });
  pool.promises[idx] = p;
  return p;
}
1034544
function Pool(config) {
	if(!(this instanceof Pool)) {
		return new Pool(config);
	}
	var self = this;
	if(!config) { throw new TypeError("config not set"); }
	self._pool = require('mysql').createPool(config);
	self._get_connection = Q.nfbind(self._pool.getConnection.bind(self._pool));
	db.Pool.call(this);
}
1322784
function(pool) {
    if (idleConnections.isEmpty()) {
      return Promise.reject(null);
    }
    const conn = idleConnections.shift();
    activeConnections[conn.threadId] = conn;
    if (
      opts.minDelayValidation <= 0 ||
      Date.now() - conn.lastUse > opts.minDelayValidation
    ) {
      return pingPromise(conn)
        .then(() => {
          return Promise.resolve(conn);
        })
        .catch(err => {
          delete activeConnections[conn.threadId];
          pool.emit('remove-conn');
          return getIdleValidConnection(pool);
        });
    } else {
      //just check connection state
      if (conn.isValid()) {
        return Promise.resolve(conn);
      } else {
        delete activeConnections[conn.threadId];
        pool.emit('remove-conn');
        return getIdleValidConnection(pool);
      }
    }
  }
935705
public void returnClient(CloseableHttpResponse resp) {
        try { 
            if (resp != null) {
                EntityUtils.consume(resp.getEntity());
            }
        } catch (IOException ex) {
            //TODO: Could not consume response completely. This is serious because the client will not be returned back to pool.
            log.error("Error returning client to pool {}", ExceptionUtils.getStackTrace(ex));
        }
    }
1302042
function receiverOnError(err) {
  const websocket = this[kWebSocket];

  websocket._socket.removeListener('data', socketOnData);

  websocket.readyState = WebSocket.CLOSING;
  websocket._closeCode = err[kStatusCode];
  websocket.emit('error', err);
  websocket._socket.destroy();
}
1344891
function errHandler(err, req, res, next) {
  console.log(addTimestamp("Internal error: " + util.inspect(err)));
  console.error(addTimestamp("Internal error: " + util.inspect(err)));
  if (err && err.stack) {
    console.error(err.stack);
  }

  var errorMessage = {
    msg: 'Internal error: ' + util.inspect(err),
    error: util.inspect(err)
  };
  if (res) {
    res.statusCode = 500;
    res.end(JSON.stringify(errorMessage));
  }

  return errorMessage;
}
1220840
function createExceptionsPattern(exceptions) {
    let pattern = "";

    /*
     * A space or an exception pattern sequence.
     * []                 ==> "\s"
     * ["-"]              ==> "(?:\s|\-+$)"
     * ["-", "="]         ==> "(?:\s|(?:\-+|=+)$)"
     * ["-", "=", "--=="] ==> "(?:\s|(?:\-+|=+|(?:\-\-==)+)$)" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5Cs%7C(%3F%3A%5C-%2B%7C%3D%2B%7C(%3F%3A%5C-%5C-%3D%3D)%2B)%24)
     */
    if (exceptions.length === 0) {

        // a space.
        pattern += "\\s";
    } else {

        // a space or...
        pattern += "(?:\\s|";

        if (exceptions.length === 1) {

            // a sequence of the exception pattern.
            pattern += escapeAndRepeat(exceptions[0]);
        } else {

            // a sequence of one of the exception patterns.
            pattern += "(?:";
            pattern += exceptions.map(escapeAndRepeat).join("|");
            pattern += ")";
        }
        pattern += `(?:$|[${Array.from(astUtils.LINEBREAKS).join("")}]))`;
    }

    return pattern;
}
53964
public static synchronized void exception(String poolName, Object mcp, Object cl, Throwable exception)
   {
      if (!confidential)
         log.tracef("%s", new TraceEvent(poolName,
                                         Integer.toHexString(System.identityHashCode(mcp)),
                                         TraceEvent.EXCEPTION,
                                         Integer.toHexString(System.identityHashCode(cl)),
                                         toString(exception)));
   }
960420
function(token,options){
      options = options||{};
      options.token = token;
      var obj = {
        type:"rest"
        ,args:{ 
          url: '/v1/sync',
          data: options,
          method: 'get' 
        }
      };

      var s = through();

      repipe(s,function(err,last,done){
        o.log('repipe got error? ',err,' should i repipe?');
        if(err && err.code != 'E_MDM') return done(err);

        getConnection(function(err,con){
          if(err) return done(err);
          var dbstream = con.mdm.createReadStream(obj);

          var noendstream = dbstream.pipe(through(function(data){
            this.queue(data);
          },function(){
            if(options.tail || options.tail == undefined) {
              // repipe resumes the stream on error events!

              var error = new Error("never end bro!");
              error.code = "E_MDM";

              this.emit("error",error);
            } else {
              this.queue(null);
            }
          }));

          dbstream.on('error',function(err){
            noendstream.emit("error",err)
          });

          done(false,noendstream);
        });
      });

      s.on('data',function(d){
        // on reconnect start sync from where i left off.
        obj.args.data.start = d.time;
      })
      return s;
    }