使用 try/catch 处理 async/await 错误,Promise 链末尾添加 .catch(),避免吞掉错误,统一封装错误处理机制以提升异步代码健壮性。

JavaScript中的异步错误处理需要特别注意,因为错误可能不会在预期的位置被捕获。以下是几种被广泛认可的最佳实践,能帮助你写出更健壮的异步代码。
使用 try/catch 包裹 async/await
在 async 函数中,推荐使用 try/catch 来捕获异步操作中的错误。这种方式让异步代码看起来像同步代码,逻辑更清晰。
例如:
async function fetchData() {
try {
const response = await fetch('/api/data');
if (!response.ok) throw new Error('请求失败');
const data = await response.json();
return data;
} catch (error) {
console.error('获取数据出错:', error.message);
// 可以重新抛出或返回默认值
}
}
确保 catch 块中处理网络错误、解析错误等所有可能异常。
为 Promise 链添加 .catch()
如果你仍在使用基于 Promise 的写法,一定要在链的末尾加上 .catch(),防止未捕获的 rejection。
立即学习“Java免费学习笔记(深入)”;
正确示例:
fetch('/api/data')
.then(res => res.json())
.then(data => console.log(data))
.catch(error => {
console.error('Promise 链出错:', error);
});
遗漏 .catch() 会导致 UnhandledPromiseRejectionWarning,在未来版本中可能直接终止程序。
避免吞掉错误
不要在 catch 块中什么都不做,这会让调试变得极其困难。
至少应该记录错误信息,必要时通知用户或上报到监控系统。
错误做法:
catch (err) {}
建议做法:
- 使用 console.error 输出错误
- 将错误发送到日志服务(如 Sentry)
- 根据上下文决定是否重新抛出错误
统一错误处理机制
对于大型项目,建议封装统一的错误处理函数,减少重复代码。
例如创建一个包装器:
function withErrorHandling(asyncFn) {
return async (...args) => {
try {
return await asyncFn(...args);
} catch (error) {
console.error('全局捕获:', error);
// 可触发通知、重试逻辑等
throw error; // 根据需要决定是否继续抛出
}
};
}
// 使用
const safeFetchData = withErrorHandling(fetchData);
基本上就这些。关键是保持一致性,确保每个异步路径都有错误出口,并让错误可追踪。










