前端错误日志记录

只记录前端页面报错,可以定位错误源 vue.config.js

1
2
3
4
configureWebpack: {
// 打包 source-map 且不泄露源码,并且报错时有组件信息而不是编译后代码的信息
devtool: 'nosources-source-map'
}

index.html

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
42
43
44
45
46
window.addEventListener("error",
function (e) {
console.log('<%= process.env.NODE_ENV %>');
if ('<%= process.env.NODE_ENV %>' === 'development') {
console.log(e)
return
}
e.stopImmediatePropagation();
var srcElement = e.srcElement;
var params = {}

var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
var isAlipay = !!u.match(/Alipay/i);
var isWechat = !!u.match(/MicroMessenger/i);
var appPlatFrom = isAndroid ? 'Android' : isiOS ? 'ios' : '';
var appFrom = (isWechat ? 'wechat_xcx' : isAlipay ? 'alipay_xcx' : '') || 'wechat_xcx';

if (srcElement !== window) {
params = {
at_time: dataFormat(new Date(), 'second'),
info: JSON.stringify({
message: '网络请求错误',
event: 'windowError',
nodeTag: srcElement.tagName,
stack: srcElement.href || srcElement.src,
}),
url: window.location.href,
from: isWechat ? '1' : isAlipay ? '3' : '5'
}
}
console.log(params);
Ajax({
method: 'POST',
url: 'https://xxx.com',
data: params,
header: [
{
key: 'appPlatFrom',
value: appPlatFrom
},
]
})
}, true
);

store.js

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
import { dataFormat } from './tools';
import store from '../store';

export default (err, vm, info) => {
if (process.env.NODE_ENV === 'development') {
console.log(err)
return
}
const time = dataFormat(new Date(), 'second')
try {
var isAlipay = !!navigator.userAgent.match(/Alipay/i);
var isWechat = !!navigator.userAgent.match(/MicroMessenger/i);
const params = {
at_time: time,
info: JSON.stringify({
message: err.message,
stack: err.stack,
nodeTag: vm.$vnode.tag,
event: info
}),
url: window.location.href,
from: isWechat ? '1' : isAlipay ? '3' : '5',
}
console.log(params);
console.log(err);
// 发送数据
store.dispatch('postErrorInfo', { data: params, callback: () => {} })
} catch (error) {
// 如果上面的处理有问题,则发送错误报告
const params = {
time,
errorInfo: error,
url: window.location.href,
}
console.log(params);
// 发送数据
store.dispatch('postErrorInfo', { data: params, callback: () => {} })
}
return false
}