移动Web开发过程中,在真机测试时,往往会遇到一些PC调试无法重现的问题,这时候我们需要在手机上拦截错误,并有相应的输出。
公司和网上都有类似的工具/类库,但如果纯粹一个简单的调试,或许不需要引入工具或类库,我们只需要知道全局拦截的原理。
其实很简单,就是window.onerror
语法:
复制代码
onerror=handleErr  
function handleErr(msg,url,l)
{
//Handle the error here
return true or false
}  
浏览器是否显示标准的错误消息,取决于 onerror 的返回值。如果返回值为 false,则在控制台 (JavaScript console) 中显示错误消息。反之则不会。
实例:
下面的例子展示如何使用 onerror 事件来捕获错误:
<html>  
<head>  
<script type="text/javascript">  
onerror=handleErr  
var txt=""  
function handleErr(msg,url,l)  
{  
txt="There was an error on this page.\n\n"  
txt+="Error: " + msg + "\n"  
txt+="URL: " + url + "\n"  
txt+="Line: " + l + "\n\n"  
txt+="Click OK to continue.\n\n"  
alert(txt)  
return true  
}  
function message()  
{  
adddlert("Welcome guest!")  
}  
</script>  
</head>  
<body>  
<input type="button" value="View message" onclick="message()" />  
</body>  
</html> 
             
             
             
			 
                                                                             
            
3 个评论
要回复文章请先登录或注册
90后IT男
90后IT男
a***@gmail.com (作者)