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时,页面不会报任何错误。
这个方法在开发阶段建议注释掉,发布的时候加上去。