有没有办法将 try-catch 添加到 Javascript 中的每个函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11742067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:12:03  来源:igfitidea点击:

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

javascripterror-handlingtry-catchprototype

提问by Wytze

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

对于错误报告,我想在我拥有的每个函数的代码周围插入一个 try-catch 包装器。

So basically I want to replace

所以基本上我想更换

function foo(arg){
   bar();
}

...with...

...和...

function foo(arg){
    try {
        bar() 
    }
    catch(e){
        customErrorHandler(e)
    }
}

Is there a way to apply this generic try-catch thing to all functions without manually editing all of them? For example by modifying the prototype of the Function object?

有没有办法在不手动编辑所有函数的情况下将这个通用的 try-catch 东西应用于所有函数?比如通过修改Function对象的原型?

EDIT

编辑

Why I want to try-catch all my functions: I am building an HTML5 app that I'm publishing on iOS and Android. I can tell from my current rudimentary javascript error reporting that even though the app runs nicely on my own device, errors do occur on some other devices.

为什么我想尝试捕获我的所有功能:我正在构建一个 HTML5 应用程序,我将在 iOS 和 Android 上发布该应用程序。我可以从我当前的基本 javascript 错误报告中看出,即使该应用程序在我自己的设备上运行良好,但在其他一些设备上确实会发生错误。

My objective is twofold: whenever a javascript error occurs on someone's device...

我的目标是双重的:每当某人的设备上发生 javascript 错误时......

  1. I want to notify the user that the app may not function perfectly
  2. I want to know roughly where the error occurred, so I know where to look for the problem
  1. 我想通知用户该应用程序可能无法完美运行
  2. 我想大致知道错误发生在哪里,所以我知道去哪里寻找问题

采纳答案by Aaron Digulla

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.

这并不简单,因为无法找到在任何地方定义的所有 JavaScript 函数。例如,任何此类方法都可能会错过在运行时定义的回调函数。

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.

您也可能不想包装所有函数,因为这将包括浏览器函数和您肯定不想包装的 JavaScript 库中的函数。

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);
    }
} );

回答by Fullchee Zhang

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

我没有足够的声誉来评论已接受的答案。

I added a returnbefore the f.applyto pass up the return value as well.

我在return之前添加了一个f.apply以传递返回值。

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

回答by Gant Laborde

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

我需要强化一些代码,所以我编写了一个名为的函数fortify并将其放入 NPM 模块中。这是一项正在进行的工作,但应该会有所帮助。

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

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

Bonus: it works with async functions. Feedback welcome

奖励:它适用于异步函数。欢迎反馈

回答by Wytze

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

好的,我似乎在这里找到了: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.

基本上,所有函数都被 try-catch 包装器替换,并在 try 部分使用原始函数。

回答by Paul Aldred-Bann

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 evalstatement.

同样,这纯粹是猜测,我还没有测试过,但如果有可能的话,我认为关键在于eval语句。