js代码分为同步和异步代码,那么它们的错误捕获是一样的吗???
try{}catch(){}捕获同步代码抛出异常
//try{}catch(){}
try {
console.log(tt);
} catch (e) {
console.log(e);//这里可以捕获到错误
}
//ReferenceError: tt is not defined
// at <anonymous>:2:14
异步异常则不能被try{}catch(){}捕获到
//error事件捕获异常
window.addEventListener('error', function(e) {
console.log(e); // 可以捕获到
}, false);
setTimeout(() => {
console.log(cc);
}, 10)
// ErrorEvent...
未被catch住的Promise抛出的错误呢
new Promise((resolve, reject) => {
console.log(rr);
resolve();
}).then(res => {
}).catch(e){
console.log(e);
}
Promise.resolve().then(res => {
console.log(rr);
}).catch(e => {
console.log(e);
})
//这样我们用catch都可以捕获到错误,那如果我们没有写catch呢
async function test(){
await setTimeout(() => {}, 10);
console.log(ee);
}
test();
//async 抛出的错误呢。我们知道async返回promise对象,
//那么也可以用.catch捕获,这个没问题
test().catch(e=>{console.log(e)})
跟上面的setTimeout抛出的异常相比,发现它们的任务源不同,导致触发的一个是宏任务一个是微任务。
//unhandledrejection事件捕获微处理的微任务抛出的异常
window.addEventListener('unhandledrejection', function(e) {
console.log(e);
}, false);
// PromiseRejectionEvent...