try…catch 指定的 try 语句块中,如果出现异常就传递到 catch 里面去。并由 catch 来处理发生的错误。
try {nonExistentFunction();} catch (error) {console.error(error);// ReferenceError: nonExistentFunction is not defined}
try {nonExistentFunction();} catch (error) {console.error(error);// ReferenceError: nonExistentFunction is not defined} finally {console.log(\\\'无论如何,我都执行。\\\')}
//message:错误信息(字符串)。//source:发生错误的脚本URL(字符串)//lineno:发生错误的行号(数字)//colno:发生错误的列号(数字)//error:Error对象(对象)window.onerror = function(errorMessage, scriptURI, lineNumber,columnNumber,errorObj) {console.log(\\\"错误信息:\\\" , errorMessage);console.log(\\\"出错文件:\\\" , scriptURI);console.log(\\\"出错行号:\\\" , lineNumber);console.log(\\\"出错列号:\\\" , columnNumber);console.log(\\\"错误详情:\\\" , errorObj);}
window.addEventListener(\\\'error\\\', function(event) { ... },true)
window.addEventListener(\\\'unhandledrejection\\\', event => {console.log(\\\'unhandledrejection:\\\' + event.reason); // 捕获后自定义处理});
类似的操作有 Vue 的 errorHandler 和 React 的 componentDidCatch,不管怎样抛出、捕获,最重要的还是监听 Bug、处理 Bug 来提升系统稳定性。
参考文档
https://blog.fundebug.com/2018/12/07/how-to-handle-frontend-error
https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalEventHandlers/onerror
https://www.baidufe.com/item/7ee009bfbcd0fe94bd3e.html
https://segmentfault.com/a/1190000014672384
原创文章,作者:小道研究,如若转载,请注明出处:https://www.sudun.com/ask/34600.html