Details about js front-end code exception monitoring and js Code monitoring

Source: Internet
Author: User

Details about js front-end code exception monitoring and js Code monitoring

Reading directory

  • What is a front-end code exception?
  • Window. onerror
  • Write a js Error Reporting Library
  • Note:
  • Disadvantages:

During normal work, js errors are a common scenario. In particular, some errors may not be tested during local testing. They can be found only after being released online, if the rescue is timely, it would be okay.

Now, it may cause great losses. If the front-end can monitor this type of error and report it in time, our problem will be better solved. So let's talk about the exception monitoring of front-end code today.

What is a front-end code exception?

Generally, syntax errors and runtime errors are displayed on the console. the browser displays the error information, as well as the file, row number, and stack information.

First, let's talk about the meaning of an exception in the front-end code. Front-end code exceptions refer to the following two situations:

1. syntax errors exist in the JS script;

2. An error occurs when the JS script is running.

Similar to this:

for(var i=0;i<l;i++){ console.log(i);}

There are two ways to capture this exception,

The first type is try... catch.

The second type is window. onerror.

Because try. catch cannot catch global error events, that is, only try and catch errors in the block will be caught by you. So here we exclude this scheme,

To use the second method, that is, the window. onerror method.

Window. onerror

Open the developer tool that comes with the browser. When an error occurs, we can get a prompt immediately and know the location of the error and the stack information of the call.

We can capture various script execution exceptions on the page through window. onerror, which can help us get useful information. However, this method has compatibility issues and the data provided on different browsers is inconsistent,

Some outdated browsers can only provide some data. Its usage is as follows:

window.onerror = function (message, url, lineNo, columnNo, error)

The meanings of the five parameters are as follows:

1. message {String} error message. Intuitive error description, but sometimes you cannot see the clues from this, especially the error message of the compressed script, which may make you more confused.

2, url {String} error corresponding to the script path, such as your http://a.js error or http:// B .js error.

3. Line Number of the lineNo {Number} error.

4. columnNo {Number} error column Number.

5. The error {Object} specific error Object contains more detailed error call stack information, which is very helpful for locating errors.

Compatibility problems

Different browsersMessageIs different.

IE10 and earlier browsers can only obtain the message, url, and lineNo parameters, but cannot obtain columnNo and error.

HoweverWindow. eventObject providesErrorLineAndErrorCharacterTo correspond to the row and column numbers.

When onerror is used, we can useArguments. callee. callerThis type of information is the most direct error information, so it must be captured and reported. We will use js for demonstration later.

Default parameter values available for different browsers:

Write a js Error Reporting Library

Now that we know the usage of window. onerror, why don't we write a js library to monitor our front-end js.

Implementation ideas:

1. Collect the five parameters of window. onerror.

2. In addition to the five parameters, you can add custom parameters.

3. Send To the backend server

Now we name our library badJsReport

The Code is as follows:

/*** Name: badJsReport. js * Version 1.1.0 * Author xianyulaodi * Address: https://github.com/xianyulaodi/badJsReport * Released on: December 22,201 6 */; (function () {'use strict '; if (window. badJsReport) {return window. badJsReport};/** default reported error message */var defaults = {msg: '', // url of the error :'', // The url line of the error: '', // the row of the error col:'', // The error column of the error :'', // specific error object};/** ajax encapsulation */function ajax (optio Ns) {options = options | {}; options. type = (options. type | "GET "). toUpperCase (); options. dataType = options. dataType | "json"; var params = formatParams (options. data); if (window. XMLHttpRequest) {var xhr = new XMLHttpRequest ();} else {var xhr = new ActiveXObject ('Microsoft. XMLHTTP ');} xhr. onreadystatechange = function () {if (xhr. readyState = 4) {var status = xhr. status; if (status> = 200 & status <300) {options. success & options. success (xhr. responseText, xhr. responseXML);} else {options. fail & options. fail (status) ;}} if (options. type = "GET") {xhr. open ("GET", options. url + "? "+ Params, true); xhr. send (null);} else if (options. type = "POST") {xhr. open ("POST", options. url, true); // sets the content type xhr when the form is submitted. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xhr. send (params) ;}/ ** formatting parameter */function formatParams (data) {var arr = []; for (var name in data) {arr. push (encodeURIComponent (name) + "=" + encodeURIComponent (data [name]);} arr. push ("v =" + Math. Random ()). replace (". "," "); return arr. join ("&");}/** merge object, and report the configured parameters together */function cloneObj (oldObj) {// copy object method if (typeof (oldObj )! = 'Object') return oldObj; if (oldObj = null) return oldObj; var newObj = new object (); for (var prop in oldObj) newObj [prop] = oldObj [prop]; return newObj;}; function extendObj () {// extension object var args = arguments; if (args. length <2) {return;} var temp = cloneObj (args [0]); // call the copy object method for (var n = 1, len = args. length; n <len; n ++) {for (var index in args [n]) {temp [index] = args [n] [index] ;}} return Temp;}/*** core code zone **/var badJsReport = function (params) {if (! Params. url) {return} window. onerror = function (msg, url, line, col, error) {// use an Asynchronous Method to avoid blocking setTimeout (function () {// not all browsers support the col parameter. If not, use window. event to be compatible with col = col | (window. event & window. event. errorCharacter) | 0; defaults. url = url; defaults. line = line; defaults. col = col; if (error & error. stack) {// If the browser has stack information, use defaults directly. msg = error. stack. toString ();} else if (arguments. callee) {// try to call Ee uses the stack information var ext = []; var fn = arguments. callee. caller; var floor = 3; // here only the layer-3 stack information is taken while (fn & (-- floor> 0) {ext. push (fn. toString (); if (fn = fn. caller) {break; // if there is a Ring} fn = fn. caller;} ext = ext. join (","); defaults. msg = error. stack. toString ();} // combined reported data, including the default reported data and custom reported data var reportData = extendObj (params. data | {}, defaults); // sends the error message to the background ajax ({url: params. url, // request address type: "POST ",/ /Request Method data: reportData, // request parameter dataType: "json", success: function (response, xml) {// code params executed after the request is successfully placed here. successCallBack & params. successCallBack (response, xml) ;}, fail: function (status) {// code params executed after a failure. failCallBack & params. failCallBack (status) ;}}) ;}, 0); return true; // The error will not be displayed on the console browser. If necessary, you can comment};} window. badJsReport = badJsReport ;})(); /* ============================== badJsReport AMD Expo Rt ========================================= */if (typeof (module )! = 'Undefined') {module. exports = window. badJsReport;} else if (typeof define = 'function' & define. amd) {define ([], function () {'use strict '; return window. badJsReport ;});}

We encapsulate native ajax and merge the reported parameter objects. And exposes a global method badJsReport.

Usage:

1. Before loading badJsReport. js to other js

2. Simple usage: (this execution method should be placed before other code execution)

BadJsReport ({url: 'http: // www.baidu.com ', // The url sent to the background * required })

3. If you need to add a new reporting parameter, or you need to know the callback sent to the background. You can use the following method

BadJsReport ({url: 'http: // www.baidu.com ', // The url sent to the background * must be data :{}, // you can add custom reporting parameters, such as the app version, browser version-you can omit successCallBack: function (response, xml) {// callback sent to the background for success,-can be omitted}, failCallBack: function (error) {// callback for failed sending to the background,-omitted }})

Note:

1. For cross-origin JS resources, window. onerror cannot obtain detailed information. You need to add additional headers to resource requests.

For a static resource request, an Access-Control-Allow-Origin header must be added, that is, an Access-Control-Allow-Origin header must be added to the backend, at the same time, when a script introduces an external link tag, you need to add one more crossorigin attribute. In this way, you can obtain accurate error information.

2. Because the final return true of the Code, if an error message is displayed, the browser will not console it. If you need the browser console, you can comment out the final return true.

Disadvantages:

For the compressed code, we get the error information, but we cannot locate the number of wrong lines. For example, jquery's source code compression only contains three lines in total. In this way, it is difficult to locate the specific location, because a row has a lot of code.

Code I put on github: https://github.com/xianyulaodi/badJsReport

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.