目前我有一个模块构建器。在此脚本的精简版本中,会触发正文单击foo()
,这会引发错误。我想将一个错误处理程序附加到整个模块对象以捕获其中抛出的任何内容,不仅在创建期间,而且在运行时。是否可以?
目前,“foo alert”出现在控制台中。我想抑制这一点,让中央记录器做必要的日志。在这种情况下,我想看到“记录”。
$(function() {
var moduleCollection = {};
//creates modules, stores them and returns for reference
function define(name, def) {
var newModule = def(); //creates the module object
moduleCollection[name] = newModule; //store
//somewhere here, i must attach some sort of
//error handlers for the module
//something like:
newModule.onerror = function(){
//execute error procedure (like logging)
console.log('logged');
}
return newModule //return as reference
}
//a module definition
var mymod = define('mymod', function() {
//foo chokes unintentionally and results into an error
function foo() {throw new Error('foo alert');}
function start() {
//a body click calls foo
$('body').on('click', function() {foo()});
}
return {start: start}
});
//start module
mymod.start()
});