Is there a way to add try-catch to every function in Javascript?

后端 未结 5 1246
心在旅途
心在旅途 2021-02-04 02:32

For error reporting, I would like to insert a try-catch wrapper around the code of every function I have.

So basically I want to replace

function foo(ar         


        
相关标签:
5条回答
  • 2021-02-04 02:56

    I wonder (this is pure speculation, so not sure if this would work) you could do something like this:

    function callTryCatch(functionSignature) {
        try {
            eval(functionSignature);
        } catch (e) {
            customErrorHandler(e);
        }
    }
    
    function entryPoint() {
        callTryCatch(function() {
            // do function logic
        });
    }
    

    Again, this is pure speculation and I haven't tested but if it's even possible I think the key lies in the eval statement.

    0 讨论(0)
  • 2021-02-04 02:58

    This isn't simple since there is no way to find all JavaScript function defined everywhere. For example, any such approach would probably miss callback functions which are defined at runtime.

    You also probably don't want to wrap all functions because that would include browser functions and functions from JavaScript libraries that you certainly don't want to wrap.

    A much better approach is probably to define a function which wraps another function:

    var tcWrapper = function(f) {
        return function() {
            try {
                f.apply(this, arguments);
            } catch(e) {
                customErrorHandler(e)
            }
        }
    }
    

    Now you can use this function to decorate anything that you want. Wrapping will become more simple if you use name spaces:

    var NS = { f: function() {  } }
    

    Just put all functions to wrap in a special namespace and then iterate over the namespace:

    $.each( NS, function(i,n) {
        var p = NS[i];
        if( typeof p === 'function' ) {
            NS[i] = tcWrapper(p);
        }
    } );
    
    0 讨论(0)
  • 2021-02-04 03:00

    Okay, I seem to have found it here: http://www.nczonline.net/blog/2009/04/28/javascript-error-handling-anti-pattern/

    Basically, all functions are replaced by a try-catch wrapper with the original function in the try part.

    0 讨论(0)
  • 2021-02-04 03:07

    I don't have enough reputation to comment on the accepted answer.

    I added a return before the f.apply to pass up the return value as well.

    var tcWrapper = function(f) {
        return function() {
            try {
                return f.apply(this, arguments);
            } catch(e) {
                customErrorHandler(e)
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-04 03:18

    I needed to go fortify some code, so I wrote a function called fortify and put it in an NPM module. It's a work in progress, but it should help.

    https://github.com/infinitered/over-armour

    Bonus: it works with async functions. Feedback welcome

    0 讨论(0)
提交回复
热议问题