Why handle exceptions?
Exceptions are uncontrollable and can affect the final rendering, but there are good reasons to do so.
-
Enhance the user experience;
-
Remote location problem;
-
Be proactive and find problems early;
-
Can not double line problems, especially mobile terminal, models, systems are a problem;
-
Perfect front-end solution, front-end monitoring system;
-
For JS, we only face the exception, the occurrence of the exception will not directly cause the JS engine crash, at most will only make the current execution of the task terminated.
Exceptions to be handled:
-
JS syntax error, code exception
-
AJAX request exception
-
Static resource loading is abnormal
-
Abnormal Promise
-
The Iframe abnormal
-
Cross-domain Script error
-
Crash and jam
Exception capture method:
-
Try catch: A try catch can catch only synchronous runtime errors, but not syntactic and asynchronous errors.
try { var a = 1; var b = a + c; } catch (e) {// Catch handlers console.log(e); // ReferenceError: c is not defined }
-
Window. error: Window. onerror provides global listening for exceptions compared to try catch
window.onerror = function(errorMessage, scriptURI, lineNo, columnNo, error) { console.log(‘errorMessage: ‘ + errorMessage); // console.log(‘scriptURI: ‘+ scriptURI); // Abnormal file path console.log(‘lineNo: ‘+ lineNo); // Abnormal line number console.log(‘columnNo: ‘+ columnNo); Console. log(‘error: ‘+ error); // Exception stack information}; console.log(a);
Catch the problem by exception:
-
Use window.error to report exceptions
Onerror = function(errorMessage, scriptURI, lineNo, columnNo, error) {var errorObj = {errorMessage: errorMessage || null, scriptURI: scriptURI || null, lineNo: lineNo || null, columnNo: columnNo || null, stack: error && error.stack ? error.stack : null }; if (XMLHttpRequest) { var xhr = new XMLHttpRequest(); xhr.open(‘post’, ‘/middleware/errorMsg’, true); Xhr.setrequestheader (‘ content-type ‘, ‘application/json’); // Set the request header xhr.send(json.stringify (errorObj)); // Send parameters}}
-
Using sourceMap: This can be set within Webpack
-
Vue supports catching global exceptions
Vue. Config. errorHandler = function (err, vm, info) {let {message, // error message name, // error name script, // error script URL line, // Error column, // error column stack // Error stack information} = err;
// VM for Vue instance that threw an exception // info for Vue specific error information, such as the lifecycle hook where the error occurredCopy the code
}