最新更新时间:2019年05月08日18:03:19
概述
资源加载出错的捕获方案
<img src="image.gif" onerror="myFunction()">
document.getElementById("myImg").addEventListener("error", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "无法加载图片。";
}
运行时出错的捕获方案
//方案一
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;
};
}
window.onerror做全局监控的跨域问题
//通过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>
参考资料