Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端异常处理 #8

Open
xchunzhao opened this issue Aug 19, 2019 · 0 comments
Open

前端异常处理 #8

xchunzhao opened this issue Aug 19, 2019 · 0 comments

Comments

@xchunzhao
Copy link
Owner

目前团队基建已经进行到异常监控这个环节,需要系统性的了解前端异常。

为什么需要处理前端异常?

  • 增强用户体验
  • 远程定位问题(异常上报,这也是我们最终需要做的)
  • 针对无法复现的问题,收集异常产生的上下文进行分析

需要处理哪些异常?

  • Javascript语法错误,代码异常
  • Ajax请求异常(前端针对ajax异常进行相应的页面处理)
  • 静态资源加载异常
  • 异步异常
  • Iframe异常
  • Script error跨域异常(cross-Origin解决)

异常如何处理

  • try/catch

try/catch只能捕获到同步的运行时异常,对语法和异步错误捕获不到。

1、语法错误在开发阶段就可以避免
2、对于异步的错误。Promise可以通过unhandledrejection全局捕获。setTimeout可以使用window.onerror捕获
  • window.onerror

window.onerror不是万能的,它不能捕获Promise异常、语法错误、静态资源异常和接口异常。也可以捕获iframe异常

<iframe src="./iframe.html" frameborder="0"></iframe>
<script>
  window.frames[0].onerror = function (message, source, lineno, colno, error) {
    console.log('捕获到 iframe 异常:',{message, source, lineno, colno, error});
    return true;
  };
</script>
  • window.addEventListener('error')

用于处理静态资源加载异常

需要注意的是,window.onerror 函数只有在返回 true 的时候,异常才不会向上抛出,否则即使是知道异常的发生控制台还是会显示 Uncaught Error: xxxxx

  • window.addEventListener('unhandledrejection')

用于处理未捕获的promise异常

  • window.addEventListener('rejectionhandled')

用于统一处理使用catch捕获的promise异常

React异常捕获

React16提供error boundaries。但是会存在几种异常捕获不到。

  • 事件处理器
  • 异步代码
  • 服务端渲染代码
  • error boundaries区域内的代码

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant