先创建公共文件error-reported.js 内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
/** * 获取前端错误信息进行上报 * @param iframe */ export function catchError (iframe) { let _this = this || window let source = '来自外层框架错误信息:' if (iframe) { _this = iframe.contentWindow source = '来自iframe内部错误信息:' } _this?.addEventListener('error', function (event) { let errorMessage = event && event.message let errrorType = event && event.type let errorStack = event && event.error && event.error.stack let errorLineno = event && event.lineno let errorColno = event && event.colno let errorHref = event && event.target && event.target.location && event.target.location.href let errorPathname = event && event.target && event.target.location && event.target.location.pathname let errorParams = event && event.target && event.target.location && event.target.location.search let errorOrigin = event && event.target && event.target.location && event.target.location.origin let errorSrcElement = event && event.srcElement && event.srcElement.src // 可忽略错误,不会在控制台打印,不会中断程序 if (errorMessage === 'ResizeObserver loop limit exceeded') return let errorInfo = { source: source, // 报错来源,来自iframe内还是外层 errorMessage: errorMessage || '', // 报错信息,对应message errrorType: errrorType || '', // 报错类型,对应type errorStack: errorStack || '', // 报错定位信息,对应error->stack errorLineno: errorLineno || '', // 报错行号,对应lineno errorColno: errorColno || '', // 报错列号,对应colno errorHref: errorHref || '', // 报错完整页面url,对应target->location->href errorPathname: errorPathname || '', // 报错路径,对应target->location->pathname errorParams: errorParams || '', // 报错路径参数,对应target->location->search errorOrigin: errorOrigin || '', // 报错域,对应target->location->origin errorSrcElement: errorSrcElement || '', // 资源加载错误,对应target->srcElement->src } const info = window.JSON.stringify(errorInfo); (new Image()).src = `/api/error/report?data=${info}`; }, true) } |
然后在入口文件最前面引入error-reported.js
本文项目背景:使用art-template模板引擎建立了公共框架,使用iframe进行页面套用。所以整[……]