js异常处理

js错误处理的方式多种,比较常用的是try-catch-finally。

现在用onerror(该方法触发时有3个三个参数:ErrorMessage(错误报告消息)、URL(发生错误的URL地址)、LineNumber(错误所在行数))处理.

我们在开发阶段希望将错误信息提出出来,则可以这样子处理:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	
	<script type="text/javascript">
    window.onerror = function(sMessage, sUrl, sLine) {  
        alert("错误信息:" + sMessage + "\n错误URL: " + sUrl +  
        "\n错误Line Number: " + sLine);  
        return true;//返回true则浏览器将不会在状态栏中提示错误;默认返回false,会在状态栏提示错误信息。  
    } 
    
	</script>
  </head>
  <body>
    <input type="button" value="提交" οnclick="aa()"/>
  </body>
</html>

 上面的代码中,调用了一个不存在的aa函数,则浏览器会显示如下错误:


还有一种情况是页面代码本身没有问题,用户的过快操作,页面JS 代码还没有执行完成就直接转到其他页面也会出现这样的错误。这种错误抛给用户是相当不友好的,我们可以用下面的代码屏蔽掉所有的错误:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	
	<script type="text/javascript">
    function doNothing()
    {
    	return true;
    } 
    window.onerror = doNothing; 
    </script>
  </head>
  <body>
    <input type="button" value="提交" οnclick="aa()"/>
  </body>
</html>
 

这个时候调用不存在的函数aa时,页面不会报任何错误。

这个方法在开发阶段建议注释掉,发布的时候加上去。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值