频道直达 - 学院 - 下载 - 交易 - 特效 - 字库 - 手册 -排名-工具- 繁體
网页教学网站开发 设为首页
加入收藏
联系我们
建站搜索: 常用广告代码   用户注册 | 用户登陆
您当前的位置:中国建站之家 -> 网站开发设计技术教程 -> JavaScript教程 -> 妥善处理JavaScript中的错误

妥善处理JavaScript中的错误

作者:未知  来源:www.jz123.cn  发布时间:2007-5-14 5:40:58  发布人:圈圈

减小字体 增大字体

不管你的技术水平如何,错误或异常是应用程序开发者生活的一部分。Web开发的不连贯性留下了许多错误能够发生并确实已经发生的地方。解决的关键在于处理任何不可预见的(或可预见的错误),来控制用户的体验。利用JavaScript,就有多种技术和语言特色可以用来正确地解决任何问题。

事事检查

在开始之前检查一切是一个好的编程习惯,也就是说,你应该在利用它们之前,检查对象、方法调用等的有效性。这样就避免了与未实例化对象或对不存在的方法调用有关的错误。列表A在使用对象(变量和字段)之前会对它们进行检查。在使用字段对象之前,该脚本保证它们为有效或非空字段。

列表A

<html>
<head>
<title>JS Test</title>
<script type="text/javascript">
function validate() {
var doc = document.forms[0];
var flag = true;
if (doc != null) {
if (doc.fullName != null) {
if (doc.fullName.value == '') {
flag = false;
}
} else      {
flag = false;
}
if (doc.contactNumber != null) {
if (doc.contactNumber.value == '') {
flag = false;
}
} else {
flag = false;
}
if (flag) {
alert('Validation successful, document will be submitted.');
doc.submit();
} else {
alert('Enter values before submitting.');
} }
return 0; }
</script>
</head>
<body>
<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="validate();">
</form>
</body>
</html>

你并不需要实际地检查有效性——你可以简单地在if 语句中使用一个对象,如果它不是一个无效对象的话,所求得的值就为真。列表B就用了这种句法,同时也用到了getElementByID方法。它用了一个if语句来保证在继续之前getElementByID方法是被支持的(存在)。

列表B

<html><head>
<title>JS Test</title>
<script type="text/javascript">
function validate() {
var doc = document.forms[0];
var flag = true;
if (doc != null) {
if (doc.getElementById) {
if (doc.getElementById("fullName")) {
if (doc.fullName.value == '') {
flag = false;
}
} else {
flag = false;
}
if (doc.getElementById("contactNumber")) {
if (doc.contactNumber.value == '') {
flag = false;
}
} else {
flag = false;
}
if (flag) {
alert('Validation successful, document will be submitted.');
doc.submit()
} else {
alert('Enter values before submitting.');
} }
return 0; }
</script>
</head>
<body>
<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="validate();">
</form>
</body>
</html>

虽然在使用对象之前检查它们是一个好方法,但是有时候还是会有错误出现。在这些实例中,JavaScript语言使得发现错误变得简单,从而能够继续下去。

发现错误

和Java、C#等其他语言相类似,JavaScript中包括了try/catch/finally语句。一个try语句包含了一组代码,在这组代码中,像运行时间错误这样的异常可能会发生。catch子句概述了怎样处理错误,finally块中包括了始终被执行的代码。

一般来说,代码设法执行一组代码,如果没有执行成功的话,支配权就传到catch块。如果没有错误发生,就跳过catch块。finally块在try和catch块完毕后执行。它的句法如下:

try
{
// code
}
catch
{
// code
}
finally
{
// code
}

catch和finally块是可选的,但是如果没有catch块是没有意义的。仔细考虑列表C,它示范了try/catch/finally的用法。从被引用的字段在表格中不存在开始,错误就发生了。

列表C

<html>
<head>
<title>JS Test</title>
<script type="text/javascript">
function doIt() {
if (document.forms[0].firstName.value == '') {
// do something
}
return 0; }
</script>
</head>
<body>
<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">
</form>
</body>
</html>

一个try/catch块不能避免错误,但是它能够很得体地处理错误,这样用户就不会面对晦涩的浏览器出错信息。观察列表D。

列表D

<html>
<head>
<title>JS Test</title>
<script type="text/javascript">
function doIt() {
try {
if (document.forms[0].firstName.value == '') {
// do something
}
} catch(e) {
document.write("An unexpected error has occurred.<br><br>");
document.write("Please contact the administrator.<br><br>");
document.write(e.message);
} finally {
document.forms[0].submit();
}
return 0; }
</script></head>
<body>
<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">
</form></body></html>

它提示了以下信息,但是finally块保证了窗体的提交——不管有什么错误发生。

An unexpected error has occurred.
Please contact the administrator.
'document.forms.0.firstName.value' is null or not an object

单个catch块可以处理所有问题,但是多个catch语句可以被用来处理特定的错误。这个问题在下个部分会涉及到。

用try/catch语句可以很容易地处理不可预见的错误。在某些情况下,可能你想以不同的方式处理错误,JavaScript提供了throw语句。它的句法是很基本的——throw后面紧跟要发生的异常。这就使得你能够定义和引发自定义的异常。列表E中的代码创建了一个缺失值的异常,并且它是生成的。

列表E

<html><head>
<title>JS Test</title>
<script type="text/javascript">
function MissingValueException (errMsg) {
this.message = errMsg;
this.name="MissingValueException";
}
function doIt() {
try {
if (document.forms[0].fullName.value == '') {
noNameException = new MissingValueException("First name is missing.");
throw noNameException;
} else {
document.forms[0].submit();
}
} catch(e) {
document.write("An unexpected error has occurred.<br>");
document.write("Please contact the administrator.<br>");
document.write(e.message);
} finally {
document.forms[0].submit();
}
return 0; }
</script></head><body>
<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">
</form></body></html>

它将会显示以下信息(如果在字段中没有值输入的话):

An unexpected error has occurred.
Please contact the administrator.
First name is missing.

除此之外,你还可以用运算符instanceof来确定异常的类型,从而做出反应。列表F中的代码会检查异常对象的类型并相应地显示有关数据。

列表F

<html>
<head>
<title>JS Test</title>
<script type="text/javascript">
function MissingValueException (errMsg) {
this.message = errMsg;
this.name="MissingValueException";
}
function doIt() {
try {
if (document.forms[0].fullName.value == '') {
noNameException = new MissingValueException("First name is missing.");
throw noNameException;
}
} catch(e) {
if (e instanceofMissingValueException) {
document.write(e.message + "<br>");
document.write("Please contact the administrator.<br><br>");
} else {
document.write("An unexpected error has occurred.<br>");
document.write("Please contact the administrator.<br>");
document.write(e.message);
} } finally {
document.forms[0].submit();
} return 0; }
</script></head><body>
<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">
</form></body></html>

运算符instanceof可以同标准错误一起使用。JavaScript定义了以下标准的JavaScript错误类型:

EvalError:表明全局的eval函数使用错误。
RangeError:说明一个数值超过了所允许的值的范围。
ReferenceError:发现了一个非法的引用。
SyntaxError:发生了一个句法分析错误。
TypeError:一个操作数的实际类型与所预期的类型不同。
URIError:其中一个全局URI函数(编码URI或解码URI)使用错误。
列表G中的代码在一个catch语句中采用了TypeError类型。由于在引用字段名(document)的行中多了一个d,结果发生了一个打字错误(ddocument)。

列表G

<html><head>
<title>JS Test</title>
<script type="text/javascript">
function MissingValueException (errMsg) {
this.message = errMsg;
this.name="MissingValueException";
}
function doIt() {
try {
if (ddocument.forms[0].fullName.value == '') {
noNameException = new MissingValueException("First name is missing.");
throw noNameException;
}
} catch(e) {
if (e instanceofTypeError) {
document.write("Reference error while accessing First Name field.<br><br>");
document.write("Please contact the administrator.<br><br>");
document.write(e.message);
} else {
document.write("An unexpected error has occurred.<br><br>");
document.write("Please contact the administrator.<br><br>");
document.write(e.message);
} } finally {
document.forms[0].submit();
} return 0; }
</script></head>
<body><form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">
</form></body></html>

处理所有的页面错误

另一个你可以自行支配的特性是window.onerror事件。和所有其他的JavaScript事件一样,你可以定义一个函数或者一条代码在事件被触发时运行。它可以用来处理或忽略错误。列表H中的页面显示了遇到的所有JavaScript错误的简单信息。因为指定的函数不存在,所以当点击按钮时,错误就发生了。列表I是用onerror事件来忽略所有的错误的。

列表H

<html><head>
<title>onError Test</title>
<script type="text/javascript">
function handleErrors() {
alert("A JavaScript error has occurred.");
return true;
}
window.onerror = handleErrors;
</script></head>
<body>
<form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">
</form></body></html>

列表I

<html><head>
<title>JS Test</title>
<script type="text/javascript">
function ignoreErrors() {
return true;
}
window.onerror = ignoreErrors;
</script></head>
<body><form id="frmTest">
Name: <input id="fullName" name="fullName" type="text"><br>
Address: <input id="contactNumber" name="contactNumber" type="text"><br>
<input type="button" value="Submit" onclick="doIt();">
</form></body></html>

关于onerror事件的一个问题是浏览器的支持。最大的问题就发生在Opera浏览器中,所以在把浏览器和自己的应用程序相结合之前,你应该确保所有的目标浏览器都支持这一特性。

谨慎处理

错误是每一个应用程序的一部分,但是适当的错误处理却不是。合理地运用JavaScript的错误处理特色和自动灵活的译码可以使用户的体验更顺畅,同时也让开发方的诊断工作变得更轻松。


将本文收藏到QQ书签与更多好友分享
[打 印]
[] [返回上一页] [收 藏]
∷相关文章评论∷    (评论内容只代表网友观点,与本站立场无关!) [更多评论...]
精彩推荐
热门文章
· 注册码大全二
· 注册码大全四
· 注册码大全一
· 要10G免费网络硬盘的请进..
· 通过google 赶快来赚美金..
· 注册码大全十
· 头像-qq头像(qq新头像)4..
· 让你轻松架设FTP服务器1..
· 注册码大全三
· 梦幻背景图片7
· 卡通动物图片6
· 网页制作素材-按钮素材2..
· 让你轻松架设FTP服务器5..
· 风景图片8
· 注册码大全九
· 让你轻松架设FTP服务器2..
关注此文读者还看过
· 让你轻松架设FTP服务器4..
· 王通:网站推广的18种秘..
· Javascript实现的自动验..
· 域名突破注册方式 全球首..
· Linux内核解读入门
· 第八章 用C#写组件(rai..
· 用控件仅一条指令实现界..
· 精通数据库系列之入门-技..
· 开发者面临的.Net挑战(..
· 利用数字校正偏色图像(1..
· 挤压造型Extrusion的节点..
· 邹胜龙:网络下载企业或..
· 用排序串字段实现树状结..
· 使用AJAX技术的十大理由..
· 《高性能的数据库》 第四..
· <展现 C#> 第一章 C#简介..
相关文章
关于本站 - 网站帮助 - 广告合作 - 下载声明 - 友情连接 - 网站地图 - 人才招聘
网站合作、内容监督、商务咨询:QQ: 9576619
Copyright ? 2005--2008 中国建站之家版权所有
粤ICP备05092265号