前端监控系统
概述
在开发项目的过程中,正式环境出现了浏览器crash,这种情况在开发过程中无法复现,是一个需要长期追踪的问题,因此项目中引入了前端监控系统。
资源加载出错的捕获方案
<img src="image.gif" onerror="myFunction()">
document.getElementById("myImg").addEventListener("error", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "无法加载图片。";
}
1
2
3
4
5
6
7
运行时出错的捕获方案
//方案一
try{
let a = 0;
console.log(a)
}cache(e){
//错误信息发送给后端,保存到数据库
sendMonitorErrorInfo(JSON.stringfy(e));
}
//方案二:以react项目为例,监控某个页面的异常
componentWillMount() {
//运行时监控系统
window.onerror = function(msg, url, row, column, error) {
//console.log('完整信息无法发送给后端',error)
sendMonitorErrorInfo(msg, url, row, column, error.toString()).then( res => {
//console.log(res);
}).catch((e) => {
//console.log(e);
})
}
}
//方案三:MDN推荐的形式
componentWillMount() {
//运行时监控系统
window.onerror = function (msg, url, lineNo, columnNo, error) {
var string = msg.toLowerCase();
var substring = "script error";
if (string.indexOf(substring) > -1){
alert('Script Error: See Browser Console for Detail');
} else {
var message = [
'Message: ' + msg,
'URL: ' + url,
'Line: ' + lineNo,
'Column: ' + columnNo,
'Error object: ' + JSON.stringify(error)
].join(' - ');
alert(message);
}
return false;
};
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
window.onerror方法触发的两种场景:
代码报错
throw new Error(‘toggle window.onerror’);
window.onerror做全局监控的跨域问题
假设在www.wanshaob.com/static/a.js中做全局监控,不同域的www.hehe.com/static/b.js上报错误信息给主域名www.wanshaob.com,此时会被拦截
//通过onerror函数收集不同域的js文件的错误,需要做两个处理:
//1、设置存放js文件的服务器允许跨域,/usr/local/webserver/nginx/conf/nginx.conf的配置文件中配置以下参数:
http {
server {
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
}
}
}
//配置文件nginx.conf的完整信息
http {
include mime.types;
default_type application/octet-stream;
server {
listen 80;
server_name wanshaobo.cn;
access_log logs/1.log combined;
error_log logs/2.log warn;
location / {
root /root/html/dist;
index index.html;
try_files $uri /index.html;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8001/;
error_page 500 502 503 504 /50.html;
}
}
//2、引用相关的js文件时加上crossorigin属性
<script type="text/javascript" src="http://www.hehe.com/static/b.js" crossorigin></script>
---------------------