天天看點

前端監控系統

概述

在開發項目的過程中,正式環境出現了浏覽器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推薦的形式

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;

};

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的完整資訊

include mime.types;

default_type application/octet-stream;

listen 80;

server_name wanshaobo.cn;

access_log logs/1.log combined;

error_log logs/2.log warn;

root /root/html/dist;

index index.html;

try_files $uri /index.html;

if ($request_method = 'OPTIONS') {

return 204;

}

繼續閱讀