Skip to content

Instantly share code, notes, and snippets.

@oyvindkinsey
Created August 22, 2012 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oyvindkinsey/3429062 to your computer and use it in GitHub Desktop.
Save oyvindkinsey/3429062 to your computer and use it in GitHub Desktop.
var mylib = (function() {
var api = {
provide: function(name, fn) {
this[name] = fn;
}
};
...
api.provide('foo', function() {
...
});
api.provide('bar', function() {
...
});
return api;
})();
..
function guard(fn) {
return function() {
try {
return fn.apply(this, arguments);
} catch (e) {
// log error
}
};
}
var api = {
provide: function(name, fn) {
this[name] = guard(fn);
}
};
..
var ManagedError = function(message) {
Error.prototype.constructor.apply(this, arguments);
this.message = message;
};
ManagedError.prototype = new Error();
function guard(fn) {
return function() {
try {
return fn.apply(this, arguments);
} catch (e) {
if (e instanceof ManagedError) {
throw e;
}
// log error
}
};
}
...
api.provide('foo', function(...) {
....
throw new ManagedError('Invalid argument');
});
...
function unguard(fn) {
return function() {
try {
return fn.apply(this, arguments);
} catch (e) {
// surface the error
setTimeout(function() { throw e; }, 0);
}
};
}
function guard(fn) {
// Helper function for wrapping all functions
function wrap(fn, value) {
// not all 'function's are actually functions!
if (typeof value === 'function' && /^function/.test(value.toString)) {
return fn(value);
} else if (typeof value === 'object' && value !== null) {
for (var key in value) if (value.hasOwnProperty(key)) {
value[key] = wrap(fn, value[key]);
};
}
return value;
}
return function() {
// capture the arguments and unguard any functions
var args = Array.prototype.slice.call(arguments)
.map(function(arg) {
return wrap(unguard, arg);
});
try {
return fn.apply(this, args);
} catch (e) {
if (e instanceof ManagedError) {
throw e;
}
// log error
}
};
}
...
function guard(fn) {
// Helper function for wrapping all functions
function wrap(fn, value) {
// not all 'function's are actually functions!
if (typeof value === 'function' && /^function/.test(value.toString)) {
return fn(value);
} else if (typeof value === 'object' && value !== null) {
for (var key in value) if (value.hasOwnProperty(key)) {
value[key] = wrap(fn, value[key]);
};
}
return value;
}
return function() {
// capture the arguments and unguard any functions
var args = Array.prototype.slice.call(arguments)
.map(function(arg) {
return wrap(unguard, arg);
});
try {
return wrap(unguard, fn.apply(this, args));
} catch (e) {
if (e instanceof ManagedError) {
throw e;
}
// log error
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment