【发布时间】:2012-12-28 08:03:21
【问题描述】:
我曾经在我的 JS 类的任何方法中放置一个 try...catch:
var MyConstructor = function() {
this.init = function() {
try {
// the method code...
} catch(error) {
// the error manager log actions
}
};
// other methods, with the same try/catch usage
};
这样,保持代码接口相对简单,我认为我的代码中的任何错误都会被捕获并记录/管理。
var myInstance = new MyConstructor();
相反,每个脚本一个全局 catch 块就足够了吗? 关心抛出每个可能的(或值得注意的)错误,在我看来,知道应用程序中发生的每个错误就足够了:
// no try...catch inside the classes, but only a global try...catch per script:
try {
var myInstance = new MyConstructor();
} catch(error) {
/*
log in the needed environment
(e.g. client-side, via console, or to the server...)
*/
}
我搜索并阅读了 Stackoverflow 上的线程以及有关 JavaScript 错误管理的大量在线资源。
在这个阶段,我感兴趣的是找到找到所有错误的最佳方法,而不是管理它们以实现用户界面的优雅行为。
这不是正确的方法吗?我愿意接受任何建议。
【问题讨论】:
标签: javascript error-handling try-catch