Summary
- NodeJS 宏任务错误捕获: process.on("uncaughtException", ...)
- NodeJS 微任务错误捕获: process.on("unhandledRejection", ...)
- 浏览器上类似: window.onerror 和 window.onunhandledrejection
- 小程序上类似: wx.onError 和 wx.onUnhandledRejection
handle-error-node
js
process.on('unhandledRejection', error => {
console.warn('on unhandledRejection', error);
});
process.on('uncaughtException', error => {
console.warn('on uncaughtException', error);
});
setTimeout(() => {
fakeFuncInTimeout();
}, 0);
new Promise(() => {
fakeFuncInPromise();
});
fakeFunc();
https://codesandbox.io/s/handle-error-node-f0snv?fontsize=14&hidenavigation=1&theme=dark
handle-error-browser
js
// 以下代码有的在浏览器的 console 中直接执行有可能不会执行错误回调,
// 如果作为 JS 加载则回调正常
// 请打开 console 查看
window.onerror = (...args) => console.warn('onerror', args);
window.onunhandledrejection = (...args) =>
console.warn('onunhandledrejection', args);
setTimeout(() => {
fakeFuncInTimeout();
}, 0);
new Promise(() => {
fakeFuncInPromise();
});
fakeFunc();
// 小程序也有相似的 API
// wx.onError 和 wx.onUnhandledRejection
// Reference: https://zhuanlan.zhihu.com/p/142418902
https://codesandbox.io/s/handle-error-browser-eb4s6?fontsize=14&hidenavigation=1&theme=dark
Discussion
留言与讨论
想法、补充和不同意见都欢迎。