Executes a callback and transforms any exception raised into a sass error

@param {Function} callback
@param {Array} arguments
@api private
505553
function tryCallback(callback, args) {
  try {
    return callback.apply(this, args);
  } catch (e) {
    if (typeof e === 'string') {
      return new binding.types.Error(e);
    } else if (e instanceof Error) {
      return new binding.types.Error(e.message);
    } else {
      return new binding.types.Error('An unexpected error occurred');
    }
  }
}
406242
function handleCommandError(ex) {
    // If the command throws an exception, display the error message and command help.
    if (ex instanceof Error) {
        console.log(chalk.red(ex.message));
    } else {
        console.log(chalk.red(ex));
    }
    console.log();
    const helpArgs = {
        _: [command]
    };
    helpCommand(helpArgs);
}
940635
function execute (configs, fn, ...args) {
  if ('verbose' in configs && configs.verbose) {
    const isoDate = (new Date()).toISOString()
    console.error(COLOR_FG_YELLOW + '[' + isoDate + '] Start mongo.execute: ' + JSON.stringify([configs, fn, args]) + COLOR_RESET)
  }
  const dbConfigs = util.getDeepCopiedObject(configs)
  const mongoUrl = 'mongoUrl' in dbConfigs ? dbConfigs.mongoUrl : ''
  const dbOption = 'dbOption' in dbConfigs ? dbConfigs.dbOption : {}
  const options = 'options' in dbConfigs ? dbConfigs.options : {}
  const collectionName = 'collectionName' in dbConfigs ? dbConfigs.collectionName : ''
  delete dbConfigs.mongoUrl
  delete dbConfigs.dbOption
  delete dbConfigs.collectionName
  let manager
  // wrap last argument in newCallback
  const callback = args[args.length - 1]
  const newCallback = (error, result) => {
    if ('verbose' in configs && configs.verbose) {
      const isoDate = (new Date()).toISOString()
      console.error(COLOR_FG_YELLOW + '[' + isoDate + '] Finish mongo.execute: ' + JSON.stringify([configs, fn, args]) + COLOR_RESET)
    }
    manager.close()
    callback(error, result)
  }
  args[args.length - 1] = newCallback
  manager = getCompleteManager(mongoUrl, dbOption, options, (error, manager) => {
    if (error) {
      return newCallback(error)
    }
    const collection = getCompleteCollection(manager, collectionName, dbConfigs)
    try {
      return collection[fn](...args)
    } catch (error) {
      return newCallback(error)
    }
  })
}
381650
function error(exception) {
		if (typeof customErrorHandler === 'function') {
			customErrorHandler(exception);
			return;
		}
		if (globalConfig.debug) {
			throw exception;
		} else {
			application.fire('error', {
				exception: exception
			});
		}
	}
54605
function (format, callbackFn) {
                    var self = this,
                        args =
                            [
                                format
                            ],
                        url = this.options.hostAndPort + '/page/functions/renderBase64';
                    this.options.debug && console.log('calling execute method  for %s and with %d params: %s'.grey, url, args.length, JSON.stringify(args));

                    request.post(url, {form:{ args:JSON.stringify(args)}},
                        function (error, response, body) {
                            error && console.error(error);
                            if (response && response.statusCode === 200) {
                                callbackFn && callbackFn.call(self, body);
                            }
                            else {
                                console.log('error in response %s'.red.bold, body);
                                callbackFn && callbackFn.call(self, false, body);
                            }
                        });
                    return this;
                }
472791
function invalidArgs(src, dest, options, cb) {
  // get the callback so we can give the correct errors
  // when src or dest is missing
  if (typeof dest === 'function') cb = dest;
  if (typeof src === 'function') cb = src;
  if (typeof cb !== 'function') {
    throw new TypeError('expected callback to be a function');
  }
  if (typeof src !== 'string') {
    return cb(new TypeError('expected "src" to be a string'));
  }
  if (typeof dest !== 'string') {
    return cb(new TypeError('expected "dest" to be a string'));
  }
}
1189711
function onError(callback) {
  var code = (arguments.length > 1) ? arguments[1] : 0;
  fire('open.error', code);
  if (typeof callback === 'function') {
    callback(code);
  }
  return code;
}
239011
function execute_(callback) {
    var self = this;
    self.migrate(function(err) {
        if (err) { callback(err); return; }
        try {
            var event = { model:self.model, query:self.query, type:'select' };
            var flatten = self.$flatten || (self.getLevels()===0);
            if (!flatten) {
                //get expandable fields
                var expandables = self.model.attributes.filter(function(x) { return x.expandable; });
                //get selected fields
                var selected = self.query.$select[self.model.viewAdapter];
                if (_.isArray(selected)) {
                    //remove hidden fields
                    var hiddens = self.model.attributes.filter(function(x) { return x.hidden; });
                    if (hiddens.length>0) {
                        for (var i = 0; i < selected.length; i++) {
                            /**
                             * @type {QueryField}
                             */
                            var x = selected[i] instanceof QueryField ? selected[i] : new QueryField(selected[i]);
                            var hiddenField = hiddens.find(function(y) {
                                return x.getName() === y.name;
                            });
                            if (hiddenField) {
                                selected.splice(i, 1);
                                i-=1;
                            }
                        }
                    }
                    //expand fields
                    if (expandables.length>0) {
                        selected.forEach(function(x) {
                            //get field
                            var field = expandables.find(function(y) {
                                var f = x instanceof QueryField ? x : new QueryField(x);
                                return f.getName() === y.name;
                            });
                            //add expandable models
                            if (field) {
                                var mapping = self.model.inferMapping(field.name);
                                if (mapping) {
                                    self.$expand = self.$expand || [ ];
                                    var expand1 = self.$expand.find(function(x) {
                                        return x.name === field.name;
                                    });
                                    if (typeof expand1 === 'undefined') {
                                        self.expand(mapping);
                                    }
                                }

                            }
                        });
                    }
                }
            }
        }
        catch(err) {
            return callback(err);
        }

        //merge view filter. if any
        if (self.$view) {
            return self.model.filter({ $filter: self.$view.filter, $order:self.$view.order, $group:self.$view.group }, function(err, q) {
                if (err) {
                    if (err) { callback(err); }
                }
                else {
                    //prepare current filter
                    if (q.query.$prepared) {
                        if (event.query.$where)
                            event.query.prepare();
                        event.query.$where = q.query.$prepared;
                    }
                    if (q.query.$group)
                    //replace group fields
                        event.query.$group = q.query.$group;
                    //add order fields
                    if (q.query.$order) {
                        if (_.isArray(event.query.$order)) {
                            q.query.$order.forEach(function(x) { event.query.$order.push(x); });
                        }
                        else {
                            event.query.$order = q.query.$order;
                        }
                    }
                    //execute query
                    return finalExecuteInternal_.call(self, event, callback);
                }
            });
        }
        else {
            //execute query
            return finalExecuteInternal_.call(self, event, callback);
        }
    });
}
223163
function(params, callback) {
      var t = this;
      if (params === '.break' && t.shellCmd) {
        t.shellCmd.kill();
      }
      if (NEW_REPL) {
        t.stream.emit('data', params + "\n");
      } else {
        t.stream.emit('data', params);
      }
      return callback(null);
    }
557130
function processArgs(args, files = []) {
  return args.reduce((acc, arg) => {
    let stats;
    try {
      stats = fs.statSync(arg);
    } catch (err) {
      // Do nothing
    }

    // If argument is a directory, process the files inside
    if (stats && stats.isDirectory()) {
      return processArgs(
        fs.readdirSync(arg).map(file => path.join(arg, file)),
        files
      );
    }

    // If `statSync` failed, validating will handle the error
    // If the argument is a file, check if its a JSON file before validating
    if (!stats || JsonFileRegex.test(arg)) {
      acc.push(validateFile(arg));
    }

    return acc;
  }, files);
}
549053
public <T> T execute(final Object[] args, final Class<T> clazz, final boolean failOnError) {
        if (this.groovyScript != null) {
            return ScriptingUtils.executeGroovyScript(this.groovyScript, args, clazz, failOnError);
        }
        return null;
    }
1248834
function (args, callback) {
        if (ternserver && typeof args.file === 'string') {
          ternserver.delFile(args.file);
          callback({request: 'delFile'}); //$NON-NLS-1$
        } else {
          callback({request: 'delFile', message: i18nUtil.formatMessage(Messages['failedDeleteRequest'], args.file)}); //$NON-NLS-1$
        }
      }
576121
function _runEventCallback($canvas, layer, eventType, callbacks, arg) {
	// Prevent callback from firing recursively
	if (callbacks[eventType] && layer._running && !layer._running[eventType]) {
		// Signify the start of callback execution for this event
		layer._running[eventType] = true;
		// Run event callback with the given arguments
		callbacks[eventType].call($canvas[0], layer, arg);
		// Signify the end of callback execution for this event
		layer._running[eventType] = false;
	}
}
567683
function run(commandLineArgs, callback) {
    if (commandLineArgs.help) {
        printUsage();
        callback(null);
        return;
    }

    if (commandLineArgs.version) {
        console.log(`Version: ${pjson.version}`);
        callback(null);
        return;
    }

    // Search for default config file if not specified
    if (!commandLineArgs.config) {
        try {
            fs.accessSync(path.join(process.cwd(), defaultConfigFile), fs.F_OK);
            commandLineArgs.config = defaultConfigFile;
        } catch (e) {
            // Default config file does not exist.
        }
    }

    if (!commandLineArgs.to && commandLineArgs.to !== 0) {
        commandLineArgs.to = 'max';
    }
    if (commandLineArgs.to !== 'max') {
        commandLineArgs.to = Number(commandLineArgs.to).toString();
    }

    let postgratorConfig;
    if (commandLineArgs.config) {
        const configFile = (path.isAbsolute(commandLineArgs.config))
            ? commandLineArgs.config
            : path.join(process.cwd(), commandLineArgs.config);

        try {
            fs.accessSync(configFile, fs.F_OK);
        } catch (e) {
            callback(new Error(`Config file not found: ${configFile}`));
            return;
        }
        postgratorConfig = require(configFile);
    } else {
        postgratorConfig = {
            migrationDirectory: commandLineArgs['migration-directory'],
            driver: commandLineArgs.driver,
            host: commandLineArgs.host,
            port: commandLineArgs.port,
            database: commandLineArgs.database,
            username: commandLineArgs.username,
            password: commandLineArgs.password,
            options: { encrypt: commandLineArgs.secure || false },
        };
    }
    if (!postgratorConfig.migrationDirectory) {
        postgratorConfig.migrationDirectory = commandLineOptions.DEFAULT_MIGRATION_DIRECTORY;
    }
    if (!path.isAbsolute(postgratorConfig.migrationDirectory)) {
        postgratorConfig.migrationDirectory = path.join(process.cwd(), postgratorConfig.migrationDirectory);
    }

    if (!fs.existsSync(postgratorConfig.migrationDirectory)) {
        if (!commandLineArgs.config && commandLineArgs['migration-directory'] === commandLineOptions.DEFAULT_MIGRATION_DIRECTORY) {
            printUsage();
        }
        callback(new Error(`Directory "${postgratorConfig.migrationDirectory}" does not exist.`));
        return;
    }

    const detectVersionConflicts = postgratorConfig['detect-version-conflicts'] || commandLineArgs['detect-version-conflicts'];
    delete postgratorConfig['detect-version-conflicts']; // It's not postgrator but postgrator-cli setting

    let postgrator;
    try {
        postgrator = new Postgrator(postgratorConfig);
    } catch (err) {
        printUsage();
        callback(err);
        return;
    }

    postgrator.on(
        'validation-started',
        migration => logMessage(`verifying checksum of migration ${migration.filename}`)
    );
    postgrator.on(
        'migration-started',
        migration => logMessage(`running ${migration.filename}`)
    );

    let databaseVersion = null;

    const migratePromise = postgrator.getMigrations()
        .then((migrations) => {
            if (!migrations || !migrations.length) {
                throw new Error(`No migration files found from "${postgratorConfig.migrationDirectory}"`);
            }
            if (detectVersionConflicts) {
                const conflictingMigrations = getConflictingMigrations(migrations);
                if (conflictingMigrations && conflictingMigrations.length > 0) {
                    const conflictingMigrationFileNames = getMigrationFileNames(conflictingMigrations);
                    const conflictingMigrationFileNamesString = conflictingMigrationFileNames.join('\n');
                    throw new Error(`Conflicting migration file versions:\n${conflictingMigrationFileNamesString}`);
                }
            }
        })
        .then(() => {
            return postgrator.getDatabaseVersion().catch(() => {
                logMessage('table schemaversion does not exist - creating it.');
                return 0;
            });
        })
        .then((version) => {
            databaseVersion = version;
            logMessage(`version of database is: ${version}`);
        })
        .then(() => {
            if (commandLineArgs.to === 'max') {
                return postgrator.getMaxVersion();
            }
            return commandLineArgs.to;
        })
        .then((version) => {
            logMessage(`migrating ${(version >= databaseVersion) ? 'up' : 'down'} to ${version}`);
        })
        .then(() => {
            return postgrator.migrate(commandLineArgs.to);
        });

    promiseToCallback(migratePromise, (err, migrations) => {
        // connection is closed, or will close in the case of SQL Server
        if (err && typeof err === 'string') {
            err = new Error(err);
        }
        return callback(err, migrations);
    });
}
640008
function (error, response) {
        if (!_.isNull(error)) {
            error = _.createError(error);
        } else if (!_.isNull(response) && (response.status >= 400 || response.status === 0)) {
            error = _.createError(null, response);
            response = null;
        }
        callback(error, response);
    }
22862
def call_and_catch_errors(self, f, *args, **kwargs):
        
        try:
            return f(*args, **kwargs)
        except SassError as e:
            if self.live_errors:
                # TODO should this setting also capture and display warnings?
                return e.to_css()
            else:
                raise
904709
function resourcesHandlerError (args) {
        var scope = args.scope;

        // resources handler is not an AT class, no need to dispose
        scope._autoDisposeHandler = false;

        scope.$logError(scope.INVALID_RESOURCES_HANDLER, args.classpath);
    }