Search code examples
javascriptaopfunction-compositionmethod-modifier

Is there a way to inject a try catch inside a function?


Maybe some of you know about AOP, in some languages using AOP can lead you to be able to inject code after, before, or while a method is executing,etc.

What I want is to apply the same in Javascript, I am currently working on a massive app which has more than 300 ajax calls, and every time I need to do some change on the catch statement on them, I have to modify them one by one which is very tedious.

What I want to do is something like :

functionName.before("try {")

functionName.after("} catch(ex){
//dostuff
}")

Is it possible? I know there are things like .call, or the arguments object inside every function..which seem pretty meta-function (AOP) functionalities.


Solution

  • Not with before and after, but a wrap will work:

    Function.prototype.wrapTry = function(handle) {
        var fn = this;
        return function() {
            try {
                return fn.apply(this, arguments);
            } catch(e) {
                return handle(e);
            }
        };
    };
    

    Then use it like

    var safeFunction = functionName.wrapTry(doStuff);