Created
June 4, 2015 15:18
-
-
Save apisurfer/6b98b2b27fa5358c9043 to your computer and use it in GitHub Desktop.
Unify catching of exception
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// dependencies: underscore beceause of "_.each, _.keys" could be Array.forEach etc. | |
/** | |
* Wrap function inside try catch; unified try/catch | |
* @param f {function} function to wrap | |
* @param info {object} information to be passed in case of failure | |
* @return {function} new function which contains old one engulfed inside try/catch | |
*/ | |
function tryCatchWrap (f, info) { | |
var args = arguments; | |
return function () { | |
try { | |
return f.apply(this, arguments); | |
} catch (e) { | |
e.nuInfo = info; | |
console.error(e); | |
} | |
} | |
} | |
/** | |
* Wrap objects methods to catch exceptions | |
* Does not work with async callbacks! | |
* @param obj {object} wrap its methods | |
* @param layer {string} desription of where the object resides | |
* @param module {string} name of modules | |
* @return {object} original obj with newly created functions | |
*/ | |
exceptionWrap (obj, layer, module) { | |
module = module || ''; | |
var keys = _.keys(obj); | |
_.each(keys, (key) => { | |
if (typeof obj[key] === 'function') { | |
var f = obj[key], | |
nuInfo = { | |
layer: layer, | |
module: module, | |
method: key | |
}; | |
obj[key] = tryCatchWrap(f, nuInfo); | |
} | |
}); | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment