If you’re a front-end engineer, you’ve probably had to solve some stubborn online problem more than once, and you’ve tried to reproduce a user bug, probably with poor results……
How to locate the front-end line problem has always been a headache, because it occurs after a series of user operations.
The error may be caused by the model, network environment, interface request, complex operation behavior, etc. It is difficult to reproduce when we want to solve it, so it cannot be solved naturally. Of course, these problems are not insurmountable, so let’s take a look at how to monitor and locate online problems.
What if: Are you still an unarmed frontend? Would you like to have your own surveillance system? Follow web jun step by step operation do, you can also build a belongs to their own front-end monitoring system.
Webfunny is an open source project. Take a look at the results on the homepage (or visit www.webfunny.cn to see the results) :
Home overview map
JS Error monitoring function (Data overview)
It takes a lot of effort to look at the front end every day, and it’s hard to tell if it’s happening today or if it’s always there. In fact, front-end projects have some errors every day, such as: script error. We can neither control nor affect our business, just keep it there. So our front-end application, every day there will be a certain amount of error data. As long as the daily activity does not fluctuate too much, the error data will be relatively stable, so I choose to compare with the error data reported 7 days ago. If there is a sharp increase, I need to pay attention to this project, rather than checking the specific error data every day.
Front-end project error statistics chart
For front-end applications, Js errors directly affect the quality of front-end applications. The monitoring of front-end anomaly is an important part of the whole front-end monitoring system. Front-end exceptions include many cases: 1. Js compile-time exceptions (development stage can be excluded); 2. Js runtime exception; 3. Static resource loading exception (path write error, resource server exception, CDN exception, cross-domain exception); 4. The interface request is abnormal. In this article we will only cover Js runtime exceptions.
Monitoring process: Monitor errors -> collect errors -> Store errors -> analyze errors -> alarm errors -> Locate errors -> Resolve errors
First of all, we should have a general understanding of THE Js error situation, so that we can timely understand the health of the front-end project. Therefore, we need to analyze some necessary data, as shown in the figure below:
Analysis data of errors reported by front-end projects
So how do we monitor this data? In fact, the following three methods are mainly used:
1) Rewrite the window.onerror method, as we all know, monitoring JS errors is indispensable to it, someone has carried out a test on him, test introduction feeling is also more careful.
2) Rewrite the console.error method. I can’t give a clear answer. If the Js code injected into the browser for the first time is wrong, window.onerror cannot be detected, so I have to rewrite the console.error method to catch. Maybe there’s a better way. After window.onerror succeeds, this method is no longer needed.
3) rewrite window. Onunhandledrejection method. When you use a Promise and forget to write reject, the system always throws an Unhandled Promise rejection. No stack, no other information, especially when writing a FETCH request can easily happen. So we need to rewrite this method to help us monitor for such errors
The following is to do JS error monitoring code, we can refer to:
Var oldError = console.error; console.error = function (tempErrorMsg) { var errorMsg = (arguments[0] && arguments[0].message) || tempErrorMsg; var lineNumber = 0; var columnNumber = 0; var errorObj = arguments[0] && arguments[0].stack; if (! errorObj) { siftAndMakeUpMessage("console_error", errorMsg, WEB_LOCATION, lineNumber, columnNumber, "CustomizeError: " + errorMsg); } else { siftAndMakeUpMessage("console_error", errorMsg, WEB_LOCATION, lineNumber, columnNumber, errorObj); } return oldError.apply(console, arguments); }; Window. onerror = function(errorMsg, url, lineNumber, columnNumber, errorObj) { jsMonitorStarted = true; var errorStack = errorObj ? errorObj.stack : null; siftAndMakeUpMessage("on_error", errorMsg, url, lineNumber, columnNumber, errorStack); }; / / rewrite onunhandledrejection to capture the unprocessed rejection error window. The onunhandledrejection = function (e) {var errorMsg = ""; var errorStack = ""; if (typeof e.reason === "object") { errorMsg = e.reason.message; errorStack = e.reason.stack; } else { errorMsg = e.reason; errorStack = ""; } siftAndMakeUpMessage("on_error", errorMsg, WEB_LOCATION, 0, 0, "UncaughtInPromiseError: " + errorStack); }Copy the code
Ajax encapsulation is simple
In order to upload this data to our server, we can’t send ajax requests with xmlHttpRequest every time, so we need to wrap a simple Ajax of our own.
this.ajax = function(method, url, param, successCallback, failCallback) { var xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); xmlHttp.open(method, url, true); xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { var res = JSON.parse(xmlHttp.responseText); typeof successCallback == 'function' && successCallback(res); } else { typeof failCallback == 'function' && failCallback(); } }; xmlHttp.send("data=" + JSON.stringify(param));}
Copy the code
Second, JS Error detailed information parsing
The purpose of JS Error statistics is, first, to understand the health status of online projects, and second, to analyze errors and help us find the problem and solve it. Therefore, how to locate the problem on the line and solve the problem is the focus of our discussion now. Below, we need to analyze several key points. Let’s take a look at the overall analysis chart first:
JS error analysis result graph
(1) The number of error occurrences — the number of occurrences is proportional to the number of users affected. If the number of occurrences and the number of users affected are high, then this is a serious bug that needs to be resolved immediately. On the contrary, if the number of times is large, the number of affected users is small. Note This error occurs only in a small number of devices and has a low priority. You can perform compatibility processing on the devices of this type when necessary. Of course, the number of visits to the IP address also tells the story.
② what errors have occurred on the page — this helps us to narrow the scope of the problem and facilitate our investigation.
③ Error stack — needless to say, this is the most important factor in locating errors. Under normal circumstances, the code is compressed, so I parse and intercept a part of the code near the error code in the background, show it, check for errors. PS: You can parse the location and snippet of the obtruded code according to sourceMap. It’s a good idea. I will add it later. In addition, although the code is compressed, it is still easy to locate the error, as shown in the figure below.
SourceMap parses source code
(4) Device information – when the error occurs, analyze the user’s browser information, system version, device model, etc., can help us quickly locate the compatible device, and improve the efficiency of solving the problem.
⑤ User footprint – by recording the specific steps of the user, you can clearly understand what happened in the time before and after the user error, which is also of great help to solve the problem. The diagram below:
User Behavior Record
Three, JS error real-time monitoring and alarm
Now that we have the ability to collect JS errors and analyze errors, we can also achieve real-time monitoring of JS errors and real-time warning, so as to prevent online accidents in the future, prevent the continuous occurrence of online accidents in time and reduce losses.
The figure above shows the number of errors reported per hour, extrapolating 24 hours forward from the current time. It also shows the number of errors reported in the same time period 7 days ago. If your project is healthy and stable, the number of errors reported in the same time period should not be too different. If the difference is too large, it indicates that there is a problem on the line, and a warning should be issued at this time to avoid the occurrence of an online accident. Demo does not add warning function, but the principle is clear, after the natural will follow.
Finally, this feature should be easy to understand and issue alerts in time to let you know about front-end problems faster.
At this point, our JS error statistics function is complete.
About Webfunny
Webfunny focuses on real-time monitoring of wechat applets, H5 front-end, PC front-end online applications, real-time monitoring of front-end web pages, front-end data analysis, error statistical analysis monitoring and BUG early warning, alarm the first time, quickly fix bugs! Support private deployment, container deployment, can support tens of millions of PV daily live!! Paying customers include yiyao, Wansai, Yibao payment and many other brand enterprises.
Copyright statement
This article is originally published by WebFunny Front-end Monitoring