This article describes how to capture and analyze JavaScriptError. If you are interested, refer to how to capture and analyze JavaScript errors.
Front-end engineers know that JavaScript has basic exception handling capabilities. We can throw new Error (), and the browser will throw an exception when we call an API Error. However, it is estimated that the vast majority of front-end engineers have not considered collecting such exception information. Anyway, as long as the refresh does not recur after a JavaScript error occurs, the user can solve the problem through refresh, And the browser will not crash. If it has not happened. This assumption was established before the Single Page App became popular. After the Single Page App is running for a period of time, the status is extremely complex. You may have entered a number of operations before coming here. Do you just need to refresh the Page? Shouldn't the previous operations be completely redone? Therefore, it is necessary to capture and analyze the exception information, and then we can modify the code to avoid affecting the user experience.
Capture exceptions
The throw new Error () We write ourselves can be captured, because we know exactly where the throw is written. However, exceptions that occur when you call the browser API are not so easy to capture. Some APIs throw exceptions in the standard, and some APIs throw exceptions only in some browsers due to implementation differences or defects. For the former, we can also capture through try-catch. For the latter, we must listen to global exceptions and then capture them.
Try-catch
If some browser APIs are known to throw an exception, we need to put the call in try-catch to prevent the entire program from entering the invalid state due to an error. For example, window. localStorage is an API that throws an exception when the write data exceeds the capacity limit. This is also true in Safari's private browser mode.
The Code is as follows:
Try {
LocalStorage. setItem ('date', date. now ());
} Catch (error ){
ReportError (error );
}
Another common use case of try-catch is callback. Because the code of the callback function is uncontrollable, we do not know the code quality and whether to call other APIs that will throw exceptions. In order not to make other code after callback unable to be executed because of a callback error, it is necessary to put the call back into try-catch.
The Code is as follows:
Listeners. forEach (function (listener ){
Try {
Listener ();
} Catch (error ){
ReportError (error );
}
});
Window. onerror
If an exception occurs, try-catch can only be captured through window. onerror.
The Code is as follows:
Window. onerror =
Function (errorMessage, scriptURI, lineNumber ){
ReportError ({
Message: errorMessage,
Script: scriptURI,
Line: lineNumber
});
}
Be careful not to use window. addEventListener or window. attachEvent to listen for window. onerror. Many browsers only implement window. onerror, or only the implementation of window. onerror is standard. Considering that the standard draft defines window. onerror, we can use window. onerror.
Attribute loss
Suppose we have a reportError function to collect caught exceptions and send them to the server for storage in batches for query and analysis. What information do we want to collect? Useful information includes: Error Type (name), error message, script, line, and column) stack ). If an exception is captured through try-catch, the information is on the Error object (supported by mainstream browsers), so reportError can also collect the information. However, if the event function is captured through window. onerror, we all know that this event function has only three parameters, so information other than the three parameters is lost.
Serialize messages
If the Error object is created by ourselves, the error. message is controlled by us. Basically, what we put in error. message is what the first parameter of window. onerror is. (The browser will actually slightly modify it, for example, adding the 'uncaught Error: 'prefix .) Therefore, we can serialize the attributes we are concerned with (for example, JSON. Stringify) and store them in error. message. Then we can read window. onerror and deserialize it. Of course, this is limited to Error objects created by ourselves.
Fifth Parameter
Browser vendors also know the restrictions imposed on the use of window. onerror, so they began to add new parameters to window. onerror. Considering that only row numbers without column numbers do not seem very symmetric, IE first adds the column numbers and places them in the fourth parameter. However, you are more concerned about whether you can obtain the complete stack. So Firefox should put the stack in the fifth parameter. But Chrome said it would be better to put the entire Error object in the fifth parameter. You can read any attribute, including custom attributes. As a result, Chrome is fast, and a new window. onerror signature is implemented in Chrome 30, the standard draft is written like this.
The Code is as follows:
Window. onerror = function (
ErrorMessage,
ScriptURI,
LineNumber,
ColumnNumber,
Error
){
If (error ){
ReportError (error );
} Else {
ReportError ({
Message: errorMessage,
Script: scriptURI,
Line: lineNumber,
Column: columnNumber
});
}
}
Attribute Normalization
The names of the Error object attributes we discussed earlier are all based on the Chrome naming method. However, the names of Error object attributes vary in different browsers, for example, the script file address is called script in Chrome, but filename in Firefox. Therefore, we also need a special function to normalize the Error object, that is, to map different attribute names to uniform attribute names. For details, refer to this article. Although browser implementations are updated, it is not difficult to manually maintain such a ing table.
Similar to stack tracing. This attribute saves the stack information when an exception occurs in plain text. Because the text format used by each browser is different, you also need to manually maintain a regular expression, extract the identifier, script, line, and column numbers of each frame from plain text ).
Security restrictions
If you have also encountered an error with the message 'script error. ', you will understand what I am talking about. This is actually a browser's limitation on different origin Script files. The reason for this security restriction is as follows: assume that the HTML returned by an online banking user after logon is different from the HTML displayed by an anonymous user, a third-party website can put the website's URI in the script. in the src attribute. HTML cannot be parsed as JS, so the browser throws an exception, and this third-party website can determine whether the user has logged on by parsing the exception location. For this reason, the browser filters all exceptions thrown by different source Script files. Only the unchanged message 'script error. 'is filtered out, and all other attributes disappear.
For websites of a certain scale, it is normal that script files are stored on the CDN, with different origins. Now, even if you build a small website, common frameworks such as jQuery and Backbone can directly reference versions on the public CDN to accelerate user download. Therefore, this security restriction does cause some trouble. As a result, the exception information we collect from Chrome and Firefox is useless 'script error .'.
CORS
To bypass this restriction, you only need to ensure that the script file and the page itself are the same source. However, if you place a script file on a server without CDN acceleration, will the download speed be reduced? One solution is to store the script file on CDN, use XMLHttpRequest to download the content through CORS, and then create a script tag to inject it into the page. The embedded code on the page is of course the same source.
This is easy to say, but there are many details to implement. In a simple example:
The Code is as follows: