UnhandledPromiseRejection
错误信息
UnhandledPromiseRejection: 这个错误 originated 要么通过 throwing 内部的 异步函数不使用 catch 块, or 通过拒绝 Promise 哪个是 不 handled 使用 .catch()
快速摘要
Promise 是拒绝 (失败) 但你 做不 provide 错误处理函数 — rejection goes unhandled, 哪个可能 crash app.
为什么发生
Forgot 到添加 .catch() 之后 .然后() 链
Used 等待不使用 try/catch 块 in 异步函数
Promise rejection 是不 anticipated or handled
最小示例
✗ 错误代码
fetch("/api/data").then(res => res.json()).then(data => console.log(data));✓ 修复代码
fetch("/api/data")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error("Failed:", err));不使用 .catch(), network 错误 or 无效 JSON goes unhandled. 添加 .catch() gracefully handles 任何 rejection.
如何诊断
Look for .然后() 链不使用 .catch() at 端
检查异步函数 for missing try/catch 围绕等待
添加全局 unhandledrejection 事件监听器到 log unhandled rejections
如何修复
添加 .catch(err => ...) at 端的 每个 .然后() 链
Wrap 等待 calls in try/catch 内部异步函数
添加全局处理.on('unhandledRejection') 处理函数 (节点.js)
如何预防
总是 handle 两者都成功 and 失败的 异步操作
Use 异步/等待使用 try/catch for cleaner 错误 handling
相关资源
相关课程
- 异步 JavaScript
学习关于 Promise 错误 handling.