Define an error for middleware not found in the stack
484023
function NotFoundError(name) {
  Error.call(this);
  Error.captureStackTrace(this, arguments.callee);
  this.name = 'Middleware Not Found Error';
  this.message = name + ' not found in the current stack';
}
1198935
function loadMiddlewareModules (options)
  {
    var middlewareStackClasses = [];

    options.internalMiddleware.forEach (function (moduleName)
    {
      var module = require (moduleName);
      if (!module.middleware)
        util.fatal ('No middleware found on module %.', moduleName);
      if (module.options)
        extend (options, module.options);
      middlewareStackClasses.push (module.middleware);
    });

    if (options.externalMiddleware)
      options.externalMiddleware.forEach (function (info)
      {
        var module = require (info.load);
        if (module.options)
          extend (options, new module.options ());
        var target = info.before || info.after
          , i = middlewareStackClasses.indexOf (target);
        if (~i)
          util.fatal ("Can't locate the % middleware module for inserting %.", target, info.load);
        middlewareStackClasses.splice (i + (info.before ? 0 : 1), 0, module.middleware);
      });

    return middlewareStackClasses;
  }
1325436
function ErrorStackParser$$parse(error) {
	            if (typeof error.stacktrace !== 'undefined' || typeof error['opera#sourceloc'] !== 'undefined') {
	                return this.parseOpera(error);
	            } else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) {
	                return this.parseV8OrIE(error);
	            } else if (error.stack) {
	                return this.parseFFOrSafari(error);
	            } else {
	                throw new Error('Cannot parse given Error object');
	            }
	        }
569699
function (isGlobal, server, err, msg, session, resp, opts, cb) {
  let handler;
  if (isGlobal) {
    handler = server.app.get(Constants.RESERVED.GLOBAL_ERROR_HANDLER);
  } else {
    handler = server.app.get(Constants.RESERVED.ERROR_HANDLER);
  }
  if (!handler) {
    logger.debug('no default error handler to resolve unknown exception. ' + err.stack);
    utils.invokeCallback(cb, err, resp, opts);
  } else {
    if (handler.length === 5) {
      handler(err, msg, resp, session, cb);
    } else {
      handler(err, msg, resp, session, opts, cb);
    }
  }
}
1163722
function defaultErrorStrategy (env, error) {
  return {
    status: 500,
    error: error,
    data: `An unhandled error of '${error.name}' occurred at ${env.resource} - ${env.action}`
  }
}
345357
function compose () {
  // the function required by the server
  function middlewareF (req, res, end) {
    var index = 0

    // inject stats middleware
    if (middlewareF.options && middlewareF.options.stats) {
      middlewareF.stack = middlewareF.stack.map(function (mw) {
        var fn
        if (typeof mw === 'object') {
          var key = Object.keys(mw)[0]
          if (!mw[key].stats) {
            fn = {}
            fn[key] = middlewareF.options.stats(mw[key])
          }
        } else {
          if (!mw.stats) {
            fn = middlewareF.options.stats(mw)
          }
        }
        return fn
      })
    }

    // looping over all middleware functions defined by stack
    ;(function next (err) {
      var arity
      var middleware = middlewareF.stack[index++] // obtain the current middleware from the stack

      if (!middleware) {
        // we are at the end of the stack
        end && end(err)
        return
      } else {
        // extract middleware from object
        if (typeof (middleware) === 'object') {
          var name = Object.keys(middleware)[0]
          if (typeof (middleware[name]) === 'function') {
            middleware = middleware[name]
          } else {
            middleware = function (req, res, next) {
              next(new Error('missing middleware'))
            }
          }
        }

        try {
          arity = middleware.length // number of arguments function middleware requires
          // handle errors
          if (err) {
            // If the middleware function contains 4 arguments than this will act as an "error trap"
            if (arity === 4) {
              middleware(err, req, res, function (err) {
                nextTick(next, err)
              })
            } else {
              // otherwise check the next middleware
              next(err)
            }
          } else if (arity < 4) {
            // process non "error trap" stack
            middleware(req, res, function (err) {
              nextTick(next, err)
            })
          } else {
            // loop over "error traps" if no error `err` is set.
            next()
          }
        } catch (e) {
          next(e)
        }
      }
    })()
  }

  middlewareF.stack = []
  middlewareF.options = compose.options || {}

  ;[].slice.call(arguments).forEach(function (a) {
    middlewareF.stack = middlewareF.stack.concat(compose.decompose(a))
  })

  // extends
  ;[ 'before', 'after', 'replace', 'remove', 'push', 'unshift', 'clone' ].forEach(function (p) {
    middlewareF[p] = compose[p]
  })

  // inject stats middleware
  if (compose.options.stats) {
    middlewareF.options = {}
    middlewareF.options.stats = compose.options.stats
  }

  return middlewareF
}
529775
function _parserPhantomJS(error){
		// start parse the error stack string
		var lines	= error.stack.split("\n").slice(1);
		var stacktrace	= [];
		lines.forEach(function(line){
			if( line.match(/\(native\)$/) ){
				var matches	= line.match(/^\s*at (.+) \(native\)/);
				stacktrace.push(new Stacktrace.Frame({
					fct	: matches[1],
					url	: 'native',
					line	: 1,
					column	: 1
				}));
			}else if( line.match(/\)$/) ){
				var matches	= line.match(/^\s*at (.+) \((.+):(\d+)\)/);
				stacktrace.push(new Stacktrace.Frame({
					fct	: matches[1],
					url	: matches[2],
					line	: parseInt(matches[3], 10),
					column	: 1
				}));
			}else{
				var matches	= line.match(/^\s*at (.+):(\d+)/);
				stacktrace.push(new Stacktrace.Frame({
					url	: matches[1],
					fct	: '<anonymous>',
					line	: parseInt(matches[2], 10),
					column	: 1
				}));
			}
		});
		return stacktrace;
	}
87077
function callbackMiddleware (req, res, next) {
  if (req.url.indexOf('callback') === -1) {
    next()
  } else if (req.url.indexOf('error') === -1) {
    res.status(200).jsonp({ created: true })
  } else {
    res.status(400).jsonp({ error: true })
  }
}
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 );
	}
1206788
function StackTrace$$fromError(error, opts) {
            opts = _merge(_options, opts);
            var gps = new StackTraceGPS(opts);
            return new Promise(function(resolve) {
                var stackframes = _filtered(ErrorStackParser.parse(error), opts.filter);
                resolve(Promise.all(stackframes.map(function(sf) {
                    return new Promise(function(resolve) {
                        function resolveOriginal() {
                            resolve(sf);
                        }

                        gps.pinpoint(sf).then(resolve, resolveOriginal)['catch'](resolveOriginal);
                    });
                })));
            }.bind(this));
        }
1020979
function nextMiddleware (factory, mw, info) {
  const {
    resolved,
    index,
    routes,
    middlewares,
    errorMiddleware,
    req,
    res,
    metrics
  } = info

  const local = {
    finished: false,
    timeout: null
  }

  // check if the request has already been resolved
  if (resolved) return

  // get the current middleware
  const current = mw[index]
  const exec = {
    name: current.functionName,
    started: Date.now(),
    ended: null,
    data: null
  }

  metrics.executions.push(exec)

  // create a next method
  const next = data => {
    clearTimeout(local.timeout)
    if (local.finished || info.resolved) return
    local.finished = true

    // add the result
    exec.ended = Date.now()
    exec.data = data

    // allow reroutes to valid named route paths
    if (_.isString(data)) {
      const route = routes[data]
      if (!route) {
        if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
          info.index = 0
          req.error = new Error(`No route found for "${data}"`)
          return nextMiddleware(factory, errorMiddleware, info)
        }
        res.end(data)
      }

      // get the correct route set
      const mwSet = route.type === ERROR_MIDDLEWARE
        ? errorMiddleware
        : middlewares

      // increment the re-route counter, set the index and go
      req.reroutes += 1
      info.index = route.index
      return nextMiddleware(factory, mwSet, info)
    }

    // check for an error passed to the next method and not
    // already in the error middleware chain. if condition met
    // start processing error middleware
    if (data instanceof Error) {
      if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
        info.index = 0
        req.error = data
        return nextMiddleware(factory, errorMiddleware, info)
      }
      res.end(data)
    }

    // check if there is any more middleware in the chain
    // if not, call end to complete the request
   return info.index === mw.length
     ? res.end()
     : nextMiddleware(factory, mw, info)
  }

  // create a timeout for the middleware if timeout > 0
  if (current.timeout > 0) {
    local.timeout = setTimeout(() => {
      local.finished = true
      req.error = new Error(current.functionName
        + ' middleware timed out')

      // add the result
      exec.ended = Date.now()
      exec.data = req.error

      // if already in error middleware and timed out
      // end the entire request, othewise move to error mw
      if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
        info.index = 0
        return nextMiddleware(factory, errorMiddleware, info)
      }
      return res.end()
    }, current.timeout)
  }

  // try to execute the resolver and if unable
  // move to error middleware. if already in error
  // middleware end the request
  try {
    info.index += 1
    current.resolver(req, res, next)
  } catch (err) {
    clearTimeout(local.timeout)
    local.finished = true
    factory.emit(EVENT_ERROR, err)
    req.error = err

    // add the result
    exec.ended = Date.now()
    exec.data = req.error

    if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
      info.index = 0
      return nextMiddleware(factory, errorMiddleware, info)
    }
    return res.end()
  }
}
562673
function(err, req, res, next) {
    err.message = err.message || 'Internal Server Error';
    err.code = err.code || res.code || 500;
    if (!_.isNumber(err.code)) {
      err.code = 500;
    }

    try {
      err.line = err.stack.split('\n')[1].match(/\(.+\)/)[0];
    } catch (e) {
      err.line = null;
    }

    var envelope = {
      meta: {
        code: err.code,
        error: {
          code: err.code,
          message: err.message,
          line: err.line
        }
      },
      data: err.message
    };

    // Set code and data
    res.code = err.code;
    res.data = envelope;

    return next();
  }
550911
function formatError(e) {
    if (!e.err) {
        return e.message
    }
    // PluginError
    if (typeof e.err.showStack === 'boolean') {
        return e.err.toString()
    }
    // Normal error
    if (e.err.stack) {
        return e.err.stack
    }
    // Unknown (string, number, etc.)
    return new Error(String(e.err)).stack
}
75133
function error(err, req, res, next) {
  // log it
  if (!test) console.error(err.stack);

  // respond with 500 "Internal Server Error".
  res.status(500);
  res.send('Internal Server Error');
}
1281776
function handleRequest(middleware, handlers, mode, checkArity, req, res, errorHandler) {
  const done = err => err && setImmediate(errorHandler, err, req, res);
  // run global middleware first, then start handling request
  // this is important to allow loggers for example to kick-in regardless
  runMiddlewareStack(middleware, req, res, (err) => {
    if (err) {
      done(err);
      return;
    }
    // try to apply supplied handlers to the requested operation
    handleOperation(handlers, mode, checkArity, req, res, done);
  });
}
1270647
function parseError(error: Error | string | string[]): StackFrame[] {
  if (error == null) {
    throw new Error('You cannot pass a null object.')
  }
  if (typeof error === 'string') {
    return parseStack(error.split('\n'))
  }
  if (Array.isArray(error)) {
    return parseStack(error)
  }
  if (typeof error.stack === 'string') {
    return parseStack(error.stack.split('\n'))
  }
  throw new Error('The error you provided does not contain a stack trace.')
}
677989
function Stack (middleware, context) {
  var handle = function (args, next) { next.call(context) }
  middleware.reverse().forEach(function (layer) {
    var child = handle
    handle = function (args, next) {
      layer(args, function () {
        child(args, next)
      })
    }
  })
  return handle
}