假设我有一个名为 myfile.js 的文件。在 myfile.js 内部我有以下代码:
$(document).on("my_custom_event", function(e)
{
my_custom_function(e);
alert(undefined[1]); // This is only to trigger an exception, it's not normally used
});
现在,我的 index.html 文件将包含该 JS 文件,并且在触发 my_custom_event 时触发该异常。
我试图对错误处理进行包罗万象,以便我可以向用户显示适当的错误消息和堆栈跟踪,以便他们可以报告问题,所以我尝试使用 window.onerror,如下所示:
window.onerror = function(msg, url, line, column, error) {
var error = {
"_type": "EXCEPT",
"_msg": "A critical error has occurred.<br/>" + msg + ((error !== undefined) ? "<br/>" + error.stack : "<br/>URL: " + url + ", line " + line)
};
$.event.trigger({type:"message_event", object:error});
};
假设 message_event 在另一个函数的其他地方处理,并向用户显示消息。 jQuery 也包含在index.html 文件中,因此一切实际上都在为此工作。上述 window.onerror 函数的潜在输出都没有提供任何有用的信息,因为它们只是遍历 jQuery 堆栈跟踪,并且没有提及 myfile.js。
有什么方法可以让我真正报告问题出在 myfile.js 中吗?它不一定要通过 window.onerror,但 myfile.js 中的 try/catch 并不是真正的选择,因为我有数百个此类函数(尽管使用正确的代码,只会在真正的错误时抛出异常)发生)并且向它们添加 try/catch 需要数周时间。
我应该提到我也尝试过使用 stacktrace.js (http://stacktracejs.com/ http://stacktracejs.com/)但它也没有提供任何有用的东西。