async/await 如何处理错误?
请说明 async/await 中多种错误处理方式的优缺点。
回答
我还是少年
1. try/catch 包裹(推荐)
async function fetchData() {
try {
const data = await fetch(url);
return await data.json();
} catch (error) {
console.error('请求失败:', error);
return fallbackData;
}
}
优点:作用域明确,可捕获多个 await 的错误;缺点:每个需要错误处理的块都要 try/catch。
2. 在调用处 catch
fetchData().catch(handleError);
优点:不污染函数内部;缺点:遗漏 catch 会导致 Unhandled Promise Rejection。
3. 辅助函数模式
function to(promise) {
return promise.then(data => [null, data]).catch(err => [err, null]);
}
const [err, data] = await to(fetch(url));
Go 语言风格,适合需要区分错误和成功值的场景。
重要:
await Promise.reject()会抛出异常,必须捕获- 多个 await 可以共享一个 try/catch
- 如果不需要某个 await 等待,使用
Promise.all并行 - 未捕获的 async 函数异常会返回一个 rejected Promise