当前位置:网站首页>Analysis of error monitoring principle
Analysis of error monitoring principle
2022-07-16 06:10:00 【Campus ascetic】
List of articles
Error monitoring
Preface
As a front end , Even if you are very careful in the development process , Self test sufficient , Under the complex operation of different users, unexpected problems of programmers will inevitably appear , Bring huge losses to the company or individuals .
At this time, a front-end error monitoring system that can report errors in time and help programmers solve errors well is essential .
Next, let's talk about common error occurrence and handling .
This article mainly focuses on the following points :
- common JS Wrong type
- common JS How to handle errors
- How to report , And the content of the report
problem :
- JS、CSS、img Wait for resource loading failure (CDN Or the picture bed hangs , Inadvertently deleted 、 The file name has changed ) How to know in real time ? Instead of users telling you ?
- How to report useful error information enables programmers to quickly locate errors and repair ? Instead of reporting some confusing information ?
- In today's engineering, there is no need to compress and deface code , How to make good use of SourceMap file , Handling error messages ?
- How did something go wrong , Don't let users help you reproduce ? Required model ? To operate steps ?
- How to better calculate the distribution of problems ( Model equipment 、 browser 、 Location 、 Bandwidth, etc. ), Choose compatibility tendency autonomously according to data ?
- …
Common mistakes
- Script error
- Grammar mistakes
- Runtime error
- Synchronization error
- Asynchronous error
- Promise error
- Network error
- Resource load error
- Custom request error
Grammar mistakes
for example , English characters are written into Chinese characters . Generally, it is easy to be found during development .

Grammatical errors cannot be trycatch Handle
try {
const error = 'error'; // Rounded semicolon
} catch(e) {
console.log(' I can't perceive mistakes ');
}
Synchronization error
JS When the engine executes the script , Push the task into the event stack in blocks , Poll fetch execution , Each event task has its own context ,
In the current context, any error in the code synchronously executed can be trycatch Capture , Ensure that the subsequent synchronization code is executed .
try {
error
} catch(e) {
console.log(e);
}
Asynchronous error
common setTimeout And other methods will create new event tasks and insert them into the event stack , To be implemented later .
therefore trycatch Unable to catch code errors in other contexts .
try {
setTimeout(() => {
error // Asynchronous error
})
} catch(e) {
console.log(' I can't perceive mistakes ');
}
In order to facilitate the analysis of errors , General use window.onerror Event to listen for errors .
It is better than trycatch The ability to capture error information should be strong .
/** * @param {String} msg Error description * @param {String} url Error file * @param {Number} row Line number * @param {Number} col Column number * @param {Object} error error Error object */
window.onerror = function (msg, url, row, col, error) {
console.log(' I know I'm wrong ');
// return true; // return true When , Exceptions will not be thrown up , The console will not output errors
};

window.onerror matters needing attention
window.onerrorYou can capture common syntax 、 Sync 、 Asynchronous error and other errors ;window.onerrorUnable to capturePromiseerror 、 Network error ;window.onerrorIt should be in all JS The script was executed before , To avoid omitting ;window.onerrorEasily covered , When dealing with callbacks, you should consider , Someone is also using this event to listen .
Network error
Because the network request is abnormal, it will not bubble , Only in the event capture phase can we get .
We can use window.addEventListener. For example code 、 Pictures are important CDN Resources are hung , It is extremely important to get feedback in time .
window.addEventListener('error', (error) => {
console.log('404 error ');
console.log(error);
// return true; // Interrupt event propagation
}, true);

For this kind of resource loading error , Enough information can be obtained in the event object , Cooperate with SMS 、 Nail nail, etc. notify the developer at the first time .
window.addEventListener('error', (e) => {
if (e.target !== window) {
// Avoid double reporting
console.log({
url: window.location.href, // Reference resource address
srcUrl: e.target.src, // Resource loading error address
})
}
}, true);
window.onerror And window.addEventListener
window.addEventListener The benefits of , Not afraid of callbacks being overwritten , You can listen to multiple callback functions , But remember to destroy to avoid memory leaks and errors .
But we can't get window.onerror So much information . Generally only window.addEventListener To monitor resource loading errors .
- Custom error for network request , It is better to report manually .
Promise error
If you are using promise At the end of the day catch Words , that onerror There's nothing we can do .
Promise.reject('promise error');
new Promise((resolve, reject) => {
reject('promise error');
});
new Promise((resolve) => {
resolve();
}).then(() => {
throw 'promise error';
});
You can also use window.onunhandledrejection or window.addEventListener("unhandledrejection") To monitor errors .
Receive one PromiseError object , You can parse reason attribute , It's kind of similar stack.
The specific compatibility processing is TraceKit.js You can see .
Reporting method
imgReportajaxReport
function report(errInfo) {
new Image().src = 'http://your-api-website?data=' + errInfo;
}
ajax The class library that should be used , Be the same in essentials while differing in minor points .
- Be careful :
imgRequest has length limit , If the data is too large, you'd better useajax.post.
Script error
Scripts that reference different domain names , If there is no special treatment , The report is wrong , Generally, browsers are in security consideration , Do not show specific errors but Script error.
For example, others have ulterior motives to quote your online non open source business code , Of course, you don't want him to know the error information in your script .
If you solve the problem of cross domain error reporting of your own scripts ?
- Switch all resources to the unified domain name , But then you lose
CDNThe advantages of . - In the script file
HTTP response headerSet inCORS.
Access-Control-Allow-Origin: You-allow-origin;- script Add... To the tag
crossoriginattribute , for example<script src="http://www.xxx.com/index.js" crossorigin></script>
Response head and crossorigin Value problem
crossorigin="anonymous"( Default ),CORSIt's not equal toYou-allow-origin, You can't takecookiecrossorigin="use-credentials"AndAccess-Control-Allow-Credentials: true,CORSCannot be set to*, energy bandcookie.
IfCORSIt's not equal toYou-allow-origin, Browser does not load js.
When you are ready for the resources that free energy can control cors when ,Script error Basically, it can be filtered out , Don't report .
So much has been said , There is also a very important theme , How to analyze the error information I can capture ?
JavaScript Error analysis
One JavaScript Errors usually consist of the following errors
- error message (error message)
- Trace stack (stack trace)


Developers can throw out a JavaScript error :
- throw new Error(‘Problem description.’)
- throw Error(‘Problem description.’) <-- equivalent to the first one
- throw ‘Problem description.’ <-- bad
- throw null <-- even worse
The second is recommended , The third and fourth browsers cannot generate traceability stacks in the above two ways .
If you can parse the error information in each line of the trace stack , The ranks are cooperating SourceMap Can't you locate each line of specific source code .
The problem is that different browsers are in the above information , There is no general standard format . The difficulty is to solve the compatibility problem .
for example window.onerror Fifth parameter error The object is 2013 Joined in WHATWG Normative .
In the early Safari and IE10 Not yet ,Firefox It's from 14 Version to join Error Object's ,chrome It's also 2013 It was newly added in the year .
The recommendation
window.onerrorIt's capture JS The best way to make mistakes , When there is a legal Error Object and trace stack .
It can also avoid some mistakes that cannot be disturbed , For example, plug-in errors and cross domain errors with incomplete information .try catchenhance , The error information thrown is relatively complete , Can make upwindow.onerrorDeficiency . But as I said before ,try catchUnable to catch asynchronous errors andpromiseerror , And don't useV8Engine performance optimization .
For example, Tencent BadJS, The following recommendations are try catch The parcel
- setTimeout and setInterval
- Event binding
- ajax callback
- define and require
- Main business entrance
Whether such a fine-grained package is needed , It depends .
SourceMap
For example, there are the following error trace stacks (stack trace)
ReferenceError: thisIsAbug is not defined
at Object.makeError (http://localhost:7001/public/js/traceKit.min.js:1:9435)
at http://localhost:7001/public/demo.html:28:12
It can be parsed into a format
[
{
"args" : [],
"url" : "http://localhost:7001/public/js/traceKit.min.js",
"func" : "Object.makeError",
"line" : 1,
"column" : 9435,
"context" : null
},
{
"args" : [],
"url" : "http://localhost:7001/public/demo.html",
"func" : "?",
"line" : 28,
"column" : 12,
"context" : null
}
]
There are rows and columns and corresponding SourceMap The file can be parsed to obtain source code information .

Analysis results

The processing code is as follows :
import {
SourceMapConsumer } from 'source-map';
// Must be initialized
SourceMapConsumer.initialize({
'lib/mappings.wasm': 'https://unpkg.com/[email protected]/lib/mappings.wasm',
});
/** * according to sourceMap File parsing source code * @param {String} rawSourceMap sourceMap file * @param {Number} line Error line in compressed code * @param {Number} column Error column in compression code * @param {Number} offset Set the number of adjacent rows returned * @returns {Promise<{context: string, originLine: number | null, source: string | null}>} * context: Source error line and up and down near offset That's ok ,originLine: The source code reports an error ,source: Source file name */
export const sourceMapDeal = async (rawSourceMap, line, column, offset) => {
// adopt sourceMap The library is converted to sourceMapConsumer object
const consumer = await new SourceMapConsumer(rawSourceMap);
// Pass in the number of rows and columns to find , Find the source file and the number of rows and columns before compression
const sm = consumer.originalPositionFor({
line, // Number of compressed rows
column, // Number of columns after compression
});
// List of all source files before compression
const {
sources } = consumer;
// According to what we found source, Find the index location in the source file list
const smIndex = sources.indexOf(sm.source);
// Find the source code in the source code list
const smContent = consumer.sourcesContent[smIndex];
// Press... On the source code string " End of line marker " Split into array form
const rawLines = smContent.split(/\r?\n/g);
let begin = sm.line - offset;
const end = sm.line + offset;
begin = begin <= 0 ? 1 : begin;
// Output source line , Because the array index is from 0 Start , Therefore, the number of rows needs -1
const context = rawLines.slice(begin - 1, end).join('\n');
// Remember to destroy
consumer.destroy();
return {
context,
originLine: sm.line,
source: sm.source,
}
};
According to SourceMap File format , You can understand this code well .
At present, the monitoring system is being developed little by little , If it works well , Will open source ...
Reference website
边栏推荐
- Experimental report on using spark to predict repeat customers
- Compilation principle - parser design
- Calculate the number of days difference between localdates, which is convenient and fast
- Nftscan Developer Platform launches Multi Chain NFT data pro API service
- Vue+axios+mysql realizes paging query, condition query and batch deletion
- Euler talk | developer community experience bureau starts at about 19:30 on July 14
- redux 源码分析
- Compilation principle - lexical analyzer design
- Open source internship | compiler sig internship task is officially released. Welcome to apply!
- Solutions to Oracle database error codes
猜你喜欢

HTTP 缓存机制详解

Arthas简介及IDEA插件快速入门

Arthas introduction and idea plug-in quick start

36.js-- prototype chain 2-- (mainly written test questions)

Compilation principle - parser design

关于 Visual Studio 2022的安装与使用

开源实习 | Compiler SIG 实习任务正式发布,欢迎报名申请!

Dense Digital Economy: using passwords to "search for pearls in the deep sea"

Convert list data to tree data

MSF infiltrates Win2003 with eternal blue
随机推荐
ES6 -- array
Unity experiment - control the movement of game objects
消息转发机制--拯救你的程序崩溃
Go简明语法汇总--入门
It's 5 days late to convert the string to time. Pit avoidance Guide
Notes on network communication security -- static routing and experiment
Mysql 主从服务器配置实验 centos7
如何导出微信聊天记录
WKWebView之离线加载以及遇到的问题
What is slow query? How to optimize?
《SMT实用指南》读书笔记1
koa 源码分析
About the installation and use of visual studio 2022
explain使用方法及结果分析
Built in function of JS array
Moss privacy computing all-in-one machine has passed 83 evaluations of Shenzhen Guojin evaluation center
录音、上传、播放音频微信小程序实践
曾入选顶会的技术完成产品化 蚂蚁链推出版权AI计算引擎
MySQL-DQL-条件查询/聚合函数/分组查询/排序查询/分页查询
网络通信安全部分笔记一