首先,相同点,都是获取代码错误信息的方法,而且2种都不能获取异步错误。比如:
try和catch
function f2() {
try {
console.log(a)
} catch (e) {
console.log(e) // a is not defined
}
}
f2()
function f2() {
try {
setTimeout(() => {
console.log(a)
}, 100)
} catch (e) {
console.log(e)
}
}
f2()
报错:Uncaught ReferenceError: a is not defined
--------------------------------
promise和catch
var c = new Promise((resolve, reject) => {
setTimeout(() => {
console.log(a)
}, 100)
}).catch(error => {
console.log(error) // b is not defined
})
var c = new Promise((resolve, reject) => {
a = b + c
}).catch(error => {
console.log(error)
})
报错:Uncaught ReferenceError: a is not defined
---------------------------------
不同点:try,catch不能捕获promise里reject出来的错误信息,比如:
function f2() {
try {
Promise.reject('出错了');
} catch(e) {
console.log(e)
}
}
f2()
报错:Uncaught (in promise) 出错了
如果需要在try,catch里获取promise里的错误时,可以这样使用:
function f2() {
try {
Promise.reject('出错了').catch(err => {
console.log('2', err)
});
console.log('1')
} catch (e) {
console.log(e)
}
}
f2()
// 1
// 2 出错了