捕获程序异常之onerror

问题描述:html5页面在电脑上打开,功能正常,没有报错,一旦嵌进微信或者APP,页面就卡住了,不好排查js问题。

预期结果:手机微信页面功能失效时,开发人员在console面板能明确看到出错信息出错链接出错行号。

解决方案1:window.onerror

探索过程

一、 写一个公用的捕获js错误的autoException.js文件

window.onerror = function(errorMessage, scriptURI, lineNumber,columnNumber,errorObj) { 
  console.log("errorMessage:"+ errorMessage);
  console.log("scriptURI:"+ scriptURI);
  console.log("lineNumber:"+ lineNumber);
  console.log("columnNumber:"+ columnNumber);
  console.log("errorObj:"+ errorObj);
}

首先,在html5页面引入index.js和autoException.js,接着,在index.js中故意引用一个未定义的变量,刷新页面,这时会在console面板看到”Script error “报错。为什么报错信息是”Script error“,不是我们想看到的出错信息呢?因为页面的域名是m.aiyingshi.com,而静态资源的域名是static.anhouse.com,存在跨域问题,因此先解决资源跨域问题。

二、解决跨域资源共享的问题Cross-Origin Resource Sharing (CORS)

1、 在服务端

1 Access-Control-Allow-Origin:*
2 Access-Control-Allow-Credentials:true

2、 在前端页面的script标签增加crossorigin="anonymous"属性。anonymous意味着,不需要证件,就可以访问文件,相当于匿名CORS;如果使用 crossorigin=“use-credentials”,则相当于带认证的 CORS。

解决方案2:抽象语法树

使用babel插件对Javascript源代码生成的AST(抽象语法树)进行转换,最终对所有的函数生成try catch包裹代码。http://foio.github.io/babel-try-catch/

原文地址:https://www.cnblogs.com/camille666/p/exception_onerror.html