返回专题

专题 2018

JS 错误监控

Summary 相关笔记

JavaScript错误处理面试题
本文目录3
  1. Summary
  2. handle-error-node
  3. handle-error-browser

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

返回首页
上一篇Grid-Flex waterfall layout下一篇JS 语法 ES6、ES7、ES8、ES9、ES10、ES11、ES12新特性

Discussion

留言与讨论

想法、补充和不同意见都欢迎。