当我们使用 xhr 请求接口,若接口不支持跨域时,浏览器会在控制台提示错误:
Access to XMLHttpRequest at 'https://xxxxxxx.' from origin 'https://xxxxxxx' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
// setTimeout中的错误
try {
setTimeout(function () {
throw new Error('error in setTimeout'); // 200ms后会把异常抛出到全局
}, 200);
} catch (err) {
console.error('catch error', err); // 不会执行
}
// Promise中的错误
try {
Promise.resolve().then(() => {
throw new Error('error in Promise.then');
});
} catch (err) {
console.error('catch error', err);
}
把 try-catch 放到异步代码的里面
// 将try-catch放到setTimeout内部
setTimeout(() => {
try {
throw new Error('error in setTimeout');
} catch (err) {
console.error('catch error', err);
}
}, 200);
// 将try-catch放到then内部
Promise.resolve().then(() => {
try {
throw new Error('error in Promise.then');
} catch (err) {
console.error('catch error', err);
}
});
// 使用Promse自带的catch捕获异常
Promise.resolve()
.then(() => {
throw new Error('error in Promise.then');
})
.catch((err) => {
console.error('Promise.catch error', err);
});
const request = async () => {
try {
const { code, data } = await somethingThatReturnsAPromise();
} catch (err) {
console.error('request error', err);
}
};
当 somethingThatReturnsAPromise()方法产生 reject 的异常时,就会被 catch 捕获到。
当然,async-await 还有一种捕获异常的方式,在通过 await 返回正确数据时,还可以顺带写上catch()捕获异常,当 somethingThatReturnsAPromise()方法异常时,就会自动进入到 catch()方法中:
const request = async () => {
try {
const { code, data } = await somethingThatReturnsAPromise().catch((err) => console.error('catch error', err));
} catch (err) {
console.error('request error', err);
}
};
但这种捕获异常后,外层的 catch()方法就捕获不到异常了,不再继续向外层冒泡了。正确的做法是,底层模块产生的错误,应当直接抛出给业务层,让业务层决定这个错误怎么处理,而不是直接吞掉.
多层 try-catch 时,会被最内层的 catch()方法捕获到,然后就不再向外层冒泡:
try {
try {
throw new Error('error');
} catch (err) {
console.error('内层的catch', err); // 内层的catch Error: error
}
} catch (err) {
console.error('最外层的catch', error);
}
参考链接:https://blog.51cto.com/u_15057811/2621893