1、监听代码错误
<script>
window.addEventListener('error', function (e) { console.log(e,e.lineno) });
</script>
window.onerror = function (e,s,l,c,error) {
console.log(e,s,l,c,error)
}
2、 跨域代码监控
跨域之后 window.onerror
根本捕获不到正确的异常信息,而是统一返回一个 Script error
,
解决方案:对 script
标签增加一个 crossorigin=”anonymous”
,并且服务器添加 Access-Control-Allow-Origin
。
<script src="http://**.**.**:9002/index.js" crossorigin=”anonymous”></script>
3、vue项目的错误监控
Vue.config.errorHandler = function (err, vm, info) {
// handle error
// `info` 是 Vue 特定的错误信息,比如错误所在的生命周期钩子
// 只在 2.2.0+ 可用
console.log(err.stack.split('\n')[1])
console.log(vm)
console.log(info)
}
4、react
在 React
中,可以使用 ErrorBoundary
组件包括业务组件的方式进行异常捕获,配合 React 16.0+
新出的 componentDidCatch API
,可以实现统一的异常捕获和日志上报。
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
// Display fallback UI
this.setState({ hasError: true });
// You can also log the error to an error reporting service
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
使用方式如下:
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
参考文章https://mp.weixin.qq.com/s/Jgq6QmzvGCTCOKXIhLNayw