参考 :
blog.csdn.net/liubangbo/a…
blog.csdn.net/qq_43497320…
// try catch 可以捕获同步错误
function run() {
try {
console.log(a)
} catch (err) {
console.log('try catch 捕获同步错误:', err)
}
}
run();
// try catch 捕获无法异步错误
function run1() {
try {
setTimeout(() => {
console.log(b)
}, 50)
} catch (err) {
console.log(' try catch 捕获异步错误:', err)
}
}
run1();
// try catch 不能捕获promise错误,promise错误由内部catch捕获
function getHttpData() {
return new Promise((resolve, reject) => {
let obj = {
status: 200,
};
if (obj.abc.status === 200) {
resolve(200);
} else {
reject(404);
}
});
}
function test() {
try {
getHttpData()
.then((res) => {
console.log("liubbc res: ", res);
})
.catch((err) => {
console.log("liubbc err: ", err);
});
} catch (error) {
console.log(error, '无法捕获内部错误')
}
}
test()
// 捕获异步错误: 用对异步代码加try catch
function getHttpData1() {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
let obj = {
status: 200,
};
if (obj.abc.status === 200) {
resolve(200);
} else {
reject(404);
}
} catch (error) {
reject(error)
}
}, 50)
});
}
function test1() {
getHttpData1()
.then((res) => {
console.log("liubbc res: ", res);
})
.catch((err) => {
console.log("liubbc err: ", err);
});
}
test1()
// 无法捕获异步错误: 使用async await
function getHttpData2() {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
let obj = {
status: 200,
};
if (obj.abc.status === 200) {
resolve(200);
} else {
reject(404);
}
} catch (error) {
reject(error)
}
}, 50)
});
}
async function test2() {
try {
const res = await getHttpData2();
console.log(res, 'res')
} catch (error) {
console.log(error, 'error')
}
}
test2()
结论:
- try catch只能捕获同步错误;
- 针对promise,错误由promise catch块捕获;
- 对于异步错误,可以由try catch包裹,reject到外层捕获