【发布时间】:2017-08-03 16:29:22
【问题描述】:
我创建了一个小型 AngularJS 应用程序,如果未注释特定行,它可能会导致某些错误。在应用程序的 HTML 中,我创建了一个内联 <script>,用于侦听 window 对象的错误事件。
<script>
window.addEventListener('error', function (error) {
console.log('====== An error occured', error);
})
</script>
在下面的代码中,我希望为所有 7 个错误调用事件侦听器(当我取消注释每个错误并运行程序时)。但是,服务 (#7) 和控制器 (#3) 中手动引发的错误不会触发事件侦听器。他们确实将错误消息打印到控制台。
// ERROR 1:
// throw new Error('manually thrown error ouside of AngularJs');
// ERROR 2 (syntax error):
// varasakfsdjklajskdfasdf var adfasdf a var adasdf
class MyController {
constructor(MyService) {
MyService.doSomething()
// ERROR 3:
// throw new Error('manually thrown error inside of AngularJs');
// ERROR 4:
// varasakfsdjklajskdfasdf var adfasdf a var adasdf
}
}
function configBlock() {
// ERROR 5:
// throw new Error('manually thrown error inside of AngularJs');
}
function runBlock() {
// ERROR 6:
// throw new Error('manually thrown error inside of AngularJs');
}
class MyService {
doSomething() {
// Error 7
// throw new Error('manually thrown error inside of AngularJs');
}
}
angular.module('app', []);
angular.module('app').controller('MyController', MyController);
angular.module('app').config(configBlock);
angular.module('app').run(runBlock);
angular.module('app').service('MyService', MyService);
这里发生了什么,如何可靠地获取每个错误以在 window object 上引发事件?
【问题讨论】:
标签: javascript angularjs error-handling