JavaScript 异常处理 [英] JavaScript Exception Handling

查看:14
本文介绍了JavaScript 异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

捕获 JavaScript 中抛出的所有异常的最佳技术是什么?

What is the best technique for catching ALL exceptions thrown within JavaScript?

显然,最好的技术是使用 try...catch.但是对于异步回调等,这可能会变得棘手.

Obviously, the best technique is to use try...catch. But with ansynchronous callbacks and so forth, that can get tricky.

我知道 IE 和 Gecko 浏览器支持 window.onerror,但是 Opera 和 Safari 呢?

I know IE and Gecko browsers support window.onerror, but what about Opera and Safari?

这里有一堆测试用例,我希望有一个集中的异常处理解决方案:

Here are a bunch of test-cases that I would like to have a central exception handling solution for:

// ErrorHandler-Test1
var test = null;
test.arg = 5;
// ErrorHandler-Test2
throw (new Error("Hello"));
// ErrorHandler-Test3
throw "Hello again";
// ErrorHandler-Test4
throw {
    myMessage: "stuff",
    customProperty: 5,
    anArray: [1, 2, 3]
};
// ErrorHandler-Test5
try {
    var test2 = null;
    test2.arg = 5;
} catch(e) {
    ErrorHandler.handleError(e);
}
// ErrorHandler-Test6
try {
    throw (new Error("Goodbye"));
} catch(e) {
    ErrorHandler.handleError(e);
}
// ErrorHandler-Test7
try {
    throw "Goodbye again";
} catch(e) {
    ErrorHandler.handleError(e);
}
// ErrorHandler-Test8
try {
    throw {
        myMessage: "stuff",
        customProperty: 5,
        anArray: [1, 2, 3]
    };
} catch(e) {
    ErrorHandler.handleError(e);
}

如果您想到任何其他测试用例,请提及它们.其中一些案例提到了 ErrorHandler.handleError 方法.这只是使用 try...catch 时的建议指南.

If you think of any other test-cases, please mention them. Several of these cases mention a ErrorHandler.handleError method. This is just a suggested guideline when using try...catch.

推荐答案

如果你使用像 jQuery 这样的库来分配你所有的事件处理程序,你可以结合使用 window.onerror 和包装 jQuery 事件处理程序代码和带有错误处理函数的就绪函数(参见:JavaScript 错误跟踪:为什么 window.onerror 不够用).

If you use a library like jQuery for assigning all your event handlers, you can use a combination of window.onerror and wrapping the jQuery event handler code and on ready function with an error handling function (see: JavaScript Error Tracking: Why window.onerror Is Not Enough).

  • window.onerror:捕获 IE 中的所有错误(以及 Firefox 中的大多数错误),但在 Safari 和 Opera 中不执行任何操作.
  • jQuery 事件处理程序:在所有浏览器中捕获 jQuery 事件错误.
  • jQuery 就绪函数:捕获所有浏览器中的初始化错误.
  • window.onerror: catches all errors in IE (and most errors in Firefox), but does nothing in Safari and Opera.
  • jQuery event handlers: catches jQuery event errors in all browsers.
  • jQuery ready function: catches initialisation errors in all browsers.

这篇关于JavaScript 异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆