In the case of the front end, it’s often the user feedback that tells you it’s wrong.

In order for the front end to be the same as the back end, the JavaScript code on the line needs to be monitored so that the front end is notified when the client’s browser is different.

What data to collect

The main principle is to avoid user sensitive fields, and collect browser version, operating system version, MSG information reported errors, etc.

How to collect errors

Front-end errors fall into two general categories,

  1. Error in code execution

  2. Error loading resource

Code execution error

The try… catch

 try {
  init();
  // code...
} catch(e){
  Reporter.send(format(e));
}
Copy the code

Try-catch is the weakest chicken, and the downside is

  1. Using a try… Catch wrap, affecting code readability.

  2. Unable to handle syntax errors

    try {
      var error = 'error';// Chinese input method;
    } catch(e) {
      console.log('I can't sense a mistake');
      console.log(e);
    }
    Copy the code
  3. Unable to handle errors in asynchrony

    try {
      setTimeout((a)= > {
        error        // Async error})}catch(e) {
      console.log('I can't sense a mistake');
      console.log(e);
    }
    Copy the code

window.onerror

Window.onerror should be a drop. Onerror can catch runtime errors, whether asynchronous or non-asynchronous.

/** * @param {String} errorMessage errorMessage * @param {String} scriptURI error file * @param {Long} lineNumber error code lineNumber * @param {Long} columnNumber columnNumber of the error code * @param {Object} errorObj details of the error, Anything */
window.onerror = function(errorMessage, scriptURI, lineNumber, columnNumber, errorObj) { 
    // code..
}
Copy the code

Disadvantages of window.onError:

  1. Failed to hear resource loading error

  2. The onError event handler can only be declared once and does not execute multiple callbacks repeatedly:

window.addEventListener(‘error’)

Window. addEventListener can listen for resource loading errors and register multiple event handlers.

var fn = window.onerror = function() {   // Can only listen for js execution errors, can not listen for resource loading errors
  console.log(arguments);
};
window.addEventListener("error", fn);    // You can listen for js execution errors and resource loading errors
window.addEventListener("error", fn);Copy the code

To capture state (the third argument is true) can catch JS execution errors, as well as tag element loading errors with SRC.

The bubbling state (the third parameter is false) can catch JS execution errors, not load errors for tag elements with SRC.

window.onerror vs window.addEventListener(‘error’)

  1. Onerror can only be declared once, whereas event handlers can bind multiple callback functions.

  2. Onerror does not listen for resource loading errors, whereas addEventListener does.

Exceptions in promises

Promise error is delicate, try… Catch, window.onerror, and widow.addEventlistener cannot listen for a promise error.

The order of errors in promise is:

  1. If there is a catch function, the catch function is used. If the catch function does not throw a new exception, then the next then considers that no error was reported, and every thing is so good continues execution.

  2. If there is no catch function, we need to register window.addeventListener (‘unhandledrejection’) to handle it.

Wechat applets app.onerror

App({
onError(msg) {
 this.monitor.onError(msg); }})Copy the code

There is no way to get the window object in wechat applet code, so window.onError cannot be used naturally. Applet officially provides the method of app.onError.

sourceMap

The production code is mixed up with Webpack and is hard to locate.

The solution is to enable Webpack’s source-map, which is a script file generated by webpack that allows the browser to track error locations.

var path = require('path');
module.exports = {
    devtool: 'source-map'.mode: 'development'.entry: './client/index.js'.output: {
        filename: 'bundle.js'.path: path.resolve(__dirname, 'client')}}Copy the code

Resource loading failure

Methods to catch resource load failures are as follows:

  1. imgObj.onerror()

  2. Performance.getentries () obtains a successfully loaded resource, and comparison can catch errors indirectly

  3. Window.addeventlistener (‘error’, fn, true) catches but does not bubble, so window.onerror does not fire, but the capture phase does

How to Report errors

  1. Ajax reporting

  2. Report using image

Generally speaking, big factories report errors by using image objects. Send a GET request using an image to report information. Because the browser has a cache for the image, the image is sent only once for the same request, avoiding repeated reports.

var entry = {};
function report(url, data) {
    if(! url || ! data) {return;
    }
    // @see http://jsperf.com/new-image-vs-createelement-img
    var image = document.createElement('img');
    var items = [];
    for (var key in data) {
        if (data[key]) {
            items.push(key + '=' + encodeURIComponent(data[key])); }}var name = 'img_' + (+new Date());
    entry[name] = image;
    image.onload = image.onerror = function () {
      console.log(arguments);
        entry[name] =
            image =
            image.onload =
            image.onerror = null;
        delete entry[name];
    };
    image.src = url + (url.indexOf('? ') < 0 ? '? ' : '&') + items.join('&');
}
Copy the code