JS uses onerror to automatically catch exceptions

Catch exceptions

    1. use try catch use window.onerror to automatically catch exceptions.
//No need to use try catch to automatically catch error messages on every line.
// (error message, source code, in which line, in which column, error thrown)
window.onerror = function (message, source, lineNom, colNom, error) {
     // First, for cross-domain js, such as CDN's, there will be no detailed error message.
     // Second, for compressed js, but also with the sourceMap backtrack to the uncompressed code rows and columns

Take the following example

    window.onerror = function (message, source, lineNom, colNom, error) {
        return true //By returning true, the red error message will not be displayed on the console.
    function aa() {
// ouput
Uncaught TypeError: Cannot read property 'dsa' of undefined
TypeError: Cannot read property 'dsa' of undefined
    at aa (test.html:25)
    at test.html:28
      1. first, for cross-domain js such as CDN, there will be no detailed error information
      1. For the error in the introduced js file, onerror will only know that there is an exception. If you want to locate the error, first set the server to support cross-domain,

access-control-allow-origin :*

      1. . Then, set the crossorigin attribute in the srcipt tag of the introduced js.

 For example, audio img link script video tag, their src attribute can be any link from any source, and all of them can be loaded. With the addition of the corssorigin property, the resources will not be loaded in the default cross-domain way, but in the **CORS** way, so that the onerror can listen to it.
      1. second, for compressed js, it is necessary to cooperate with sourceMap to reverse check the rows and columns of uncompressed code, which can only catch the errors of js runtime. Syntax error can’t catch
        window.addEventListener('error', function(e) {
            e.preventDefault() //Error messages are not displayed on the console
        }, false)//default to false, bubbling state, capture state when set to true
    1. is the state of the capture (the third parameter is true) can catch js execution error, also can catch the tag element with SRC load error. When is bubble state (the third parameter is false), js execution errors can be caught, but loading errors of tag elements with SRC cannot be caught. PreventDefault

Read More: