Skip to content

Commit

Permalink
Add option to catch plugin exceptions and continue
Browse files Browse the repository at this point in the history
  • Loading branch information
deathcap committed Jan 29, 2014
1 parent 858ff44 commit 773d84c
Showing 1 changed file with 31 additions and 7 deletions.
38 changes: 31 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ function Plugins(game, opts) {
opts = opts || {};
this.require = opts.require || require;
this.masterPluginName = opts.masterPluginName || 'voxel-cs'; // synthetic 'plugin' created as parent of all
this.catchExceptions = true;

// map plugin name to instances
this.all = {};
Expand All @@ -22,6 +23,24 @@ function Plugins(game, opts) {
this.graph = tsort();
}

Plugins.prototype.wrapExceptions = function(f) {
var ret;

if (!this.catchExceptions) {
ret = f();
return ret === undefined ? true : ret; // undefined ok
}

try {
ret = f();
} catch (e) {
console.log('caught exception:',e,'calling',f);
console.trace();
return false;
}
return ret === undefined ? true : ret;
}

// Require the plugin module and return its factory constructor
// This does not construct the plugin instance, for that see instantiate()
Plugins.prototype.scan = function(name) {
Expand Down Expand Up @@ -53,7 +72,12 @@ Plugins.prototype.scanAndInstantiate = function(name, opts) {
return false;
}

return this.instantiate(createPlugin, name, opts);
var self = this;
if (!this.wrapExceptions(function() {
return self.instantiate(createPlugin, name, opts);
})) {
console.log("failed to instantiate ",name);
}
};

// Instantiate a plugin given factory constructor, creating its instance (starts out enabled)
Expand Down Expand Up @@ -204,12 +228,12 @@ Plugins.prototype.enable = function(name) {
}

if (plugin.enable) {
//try {
if (!this.wrapExceptions(function() {
plugin.enable();
/*} catch(e) {
})) {
console.log("failed to enable:",plugin,name,e);
return false;
}*/
}
}
plugin.pluginEnabled = true;
this.emit('plugin enabled', name);
Expand All @@ -231,12 +255,12 @@ Plugins.prototype.disable = function(name) {
}

if (plugin.disable) {
//try {
if (!this.wrapExceptions(function() {
plugin.disable();
/*} catch (e) {
})) {
console.log("failed to disable:",plugin,name,e);
return false;
}*/
}
}

plugin.pluginEnabled = false;
Expand Down

0 comments on commit 773d84c

Please sign in to comment.