Catch exceptions
-
- 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
<script>
window.onerror = function (message, source, lineNom, colNom, error) {
console.log('Error')
console.log(message)
console.log(source)
console.log(lineNom)
console.log(colNom)
console.log(error)
return true //By returning true, the red error message will not be displayed on the console.
}
function aa() {
console.log('aa')
console.log(aa.nme.dsa)
console.log('aa')
}
aa()
</script>
// ouput
aa
error
Uncaught TypeError: Cannot read property 'dsa' of undefined
http://127.0.0.1:5500/test.html
25
32
TypeError: Cannot read property 'dsa' of undefined
at aa (test.html:25)
at test.html:28
-
-
- first, for cross-domain js such as CDN, there will be no detailed error information
-
-
-
- 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 :*
-
-
- . 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.
-
-
- 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) {
console.log('chucuole')
e.preventDefault() //Error messages are not displayed on the console
}, false)//default to false, bubbling state, capture state when set to true
-
- 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