Discussion on three aspects of Web front-end monitoring

Source: Internet
Author: User

A. JS Error monitoring mode

1. Active judgment

We get a desired result after some operations, but the result is not what we want.

Test.jsfunction Calc () {  //code ...  return Val;} if (Calc ()!== "Someval") {  reporter.send ({    position: "Test.js::<function>calc"    msg: "Calc Error"  });}

This feedback, which is a logical error/State error, is much more in the interface status judgment.

2. try..catch Capture

To determine the error that exists in a code snippet:

try {  init ();  Code ...} catch (e) {  reporter.send (format (e));}

To the entrance of the init program, all synchronous execution errors in the code will be captured, which is also a good way to avoid the program just run up and hang.

3.window.onerror

To catch a global error:

Window.onerror = function () {  var errinfo = format (arguments);  Reporter.send (errinfo);  return true;};

Returned in the above function return true , the error is not exposed to the console. The following is its parameter information:

/** * @param {string}  errormessage   error message * @param {string}  Scripturi      file with error * @param {Long}    LineNumber the     line number of the error code * @param {Long}    columnnumber   The column number of the error code * @param {Object}  errorobj       error details, Anything */window.onerror = function (errormessage, Scripturi, linenumber,columnnumber,errorobj) {     //code:}

window.onerroris a particularly violent fault-tolerant approach, and try..catch so, their bottom-up implementation is to use the statement in C/S, goto once the error is found, no matter how deep the current stack, regardless of where the code is run, run directly to the top layer or try..catch capture layer, This kind of kick-off error is not a good way to handle it.

There are two more points to note about Window.onerror.

    1. For onerror This global capture, it is best to write in front of all JS scripts, because you can not guarantee that the code you write error, if written in the back, if the error is not captured by OnError.
    2. Another onerror is the failure to catch a network exception.

When we encounter the 404 Network Request exception, OnError is unable to help us catch the exception.

<Script>  Window.OnError= function (msg, url, row, col, error) {  Console. log ( I know async error console. log ({ msg, url, row, col, Error})  Span class= "Pl-k" >return true;}; </script><img src=   

Because the network request exception does not bubble, so it must be captured in the capture phase to the line, but although this way can catch the exception of network requests, but it is not possible to determine whether the status of HTTP is 404 or other such as 500 and so on, so also need to cooperate with the server log for troubleshooting analysis can be.

<Script>Window.AddEventListener (' Error‘, (MsgUrlRowcol, error) => { console. log ( I know 404 error console. log ( msg, url, row, col, Error Span class= "Pl-k" >return true;}, true); </script><img src=< Span class= "pl-s" > "/404.png" alt=  "";          

This knowledge still need to know, otherwise users visit the site, image CDN can not serve, the picture is not loaded and developers are not aware of the embarrassment.

Promise Error

The Promise can help us solve the problem of the async callback hell, but once the Promise instance throws an exception and you don't capture it with catch, onerror or try-catch is powerless to catch the error.

Window.AddEventListener (' Error‘, (MsgUrlRowColError= = {Console.Log' I can't perceive the promise error‘);console. log (msg, URL, row, col, error);}, true); promise. reject ( ' promise Errornew promise ((resolve, reject) => {reject ( ' promise Errornew promise ((resolve) => {resolve ();}). then (() => {throw  "});          

Although it is a good habit to form the last catch function when writing Promise instances, it is easy to get confused and forget to write catch when the code is written too much.

So if your application uses a lot of Promise instances, especially if you have to be careful in some Promise-based asynchronous libraries like Axios, because you don't know when these asynchronous requests will throw an exception and you don't deal with it, so you'd better add a Promise Global exception capture event unhandledrejection.

Window.AddEventListener ("Unhandledrejection",functionE) {E.Preventdefault ()Console.Log' I know promise's wrong.‘);Console.Loge.reason); return true;}); promise. reject ( ' promise Errornew promise ((resolve, reject) => {reject ( ' promise Errornew promise ((resolve) => {resolve ();}). then (() => {throw  "});          

Window.onerror can catch an IFRAME error

When your page has an IFRAME, you need to do abnormal monitoring of the iframe you introduced, otherwise, once you introduce the IFRAME page has a problem, your main station will not show, and you do not know.

First of all, it is necessary to emphasize that the parent window directly using Window.onerror is not directly captured, if you want to capture an IFRAME exception, there are several cases.

If your iframe page and your main station is the same domain name, add the OnError event directly to the IFRAME.

<IframeSrc="./iframe.html"Frameborder="0"></iframe><Script> window. Frames[0]. OnError = function (msg, url, row, col, error) { console. log ( I know the error of the IFRAME, also know the error message  console. Log ({ msg, url, row, col, Error})   return true;}; </SCRIPT>        

Readers can npm run iframe see the effect by:

If you embed the IFRAME page and your main station is not the same domain name, but the content of the IFRAME is not a third party, you can control, then you can communicate with the IFRAME in the way the exception information to the main station to receive. There are many ways to communicate with the IFRAME, commonly used such as: Postmessage,hash or Name field cross-domain and so on, here do not expand, interesting words can be seen: cross-domain, you need to know all here

If it is not the same domain and the site is not under its own control, in addition to the console to see the detailed error information, no way to capture, this is for security reasons, you introduced a Baidu home page, People's pages reported errors on what let you go to monitor it, this will lead to a lot of security issues.

Exception escalation Mode

After the monitoring to get the error message, the next step is to send the captured errors to the information collection platform, commonly used in the form of two main types:

    1. Sending data via Ajax
    2. Dynamically create the form of an IMG tag

Instance-Dynamically create an IMG tag for escalation

Report (error) {  ' http://xxxx/reportImage ().     ' error=+ error;}


Collect abnormal information too much, how to do

If your website visit is very large, if the webpage of PV 1kw, then a certain error to send the information has 1kw, we can set a collection rate for the site:

 reporter. Send = function (data) {//only collect 30% if (math. Random () < 0.3) {send (data) //report error message}}             


Two. Interface Request length
    /** * Intercept interface request, escalate interface information*/    //Unified interception of AJAX requests    varstart_time = 0, Gap_time= 0;//Calculate Request DelayWindow.addeventlistener (' Ajaxreadystatechange ',function(e) {varXHR =E.detail, Status=Xhr.status, ReadyState=xhr.readystate, ResponseText=Xhr.responsetext; /** * Calculate request Delay*/         if(ReadyState = = 1) {start_time= (NewDate ()). GetTime (); }        if(ReadyState = = 4) {Gap_time= (NewDate ()). GetTime ()-start_time; }        /** * report request Information * @Author Smy * @DateTime 2018-06-27t16:32:30+0800*/        if(ReadyState = = 4) {Httpreport (gap_time, Status, Xhr.responseurl)})

Three. Page load duration

See also: https://blog.oldj.net/2012/01/09/measuring-the-user-latency/

Reference:

Https://www.cnblogs.com/hustskyking/p/fe-monitor.html

http://web.jobbole.com/93684/

Https://github.com/happylindz/blog/issues/5

Discussion on three aspects of Web front-end monitoring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.