Skip to content

Unhandled Promise Rejection

快速摘要

Promise 是拒绝 (异步操作失败) 但你 做不 handle 错误 — rejection 是 lost.

为什么发生

  • Missing 等待之前异步 call 那个拒绝

  • 否 try/catch 围绕异步 code 那个能 失败

  • Missing .catch() on Promise 链

最小示例

✗ 错误代码
async function getUser() {
  const response = await fetch('/api/user'); // May reject!
  return response.json();
}
getUser(); // Unhandled rejection if fetch fails
✓ 修复代码
async function getUser() {
  try {
    const response = await fetch('/api/user');
    return await response.json();
  } catch (error) {
    console.error('Failed:', error.message);
    return null;
  }
}
getUser();

不使用 try/catch, 失败获取 causes unhandled rejection. Wrapping 异步 code in try/catch catches 错误 and handles 它 gracefully.

如何诊断

  • Look for 'UnhandledPromiseRejection' in 错误输出

  • 检查如果异步函数有 try/catch 块

  • 验证所有 Promise 链有 .catch()

如何修复

  • Wrap 异步 code in try/catch

  • 添加 .catch() 到 Promise 链

  • Use 异步/等待使用 try/catch for cleaner 错误 handling

如何预防

  • 总是 handle 异步错误使用 try/catch or .catch()

  • 添加全局 unhandledRejection 处理函数 as safety net

相关资源

相关术语

相关课程

  • 错误

    学习关于异步错误 handling.

← 返回语言