下载首页下载分类最近更新排 行 榜国产软件国外软件汉化补丁本站论坛BT下载页
  • 设为首页
  • 收藏本站
  • 联系我们
您的位置:首页网页制作JS/Ajax → 妥善处理JavaScript中的错误
妥善处理JavaScript中的错误
出处:本站整理 作者:佚名 日期:2007-5-7 15:29:29 人气: [ ]

不管你的技术水平如何,错误或异常是应用程序开发者生活的一部分。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的错误处理特色和自动灵活的译码可以使用户的体验更顺畅,同时也让开发方的诊断工作变得更轻松。

相关文章
相关软件
评论人 评论内容摘要(共 0 条,查看完整内容) 得分 0 发表时间
关于本站 | 广告服务 | 版权声明 | 联系我们 | | 联系我 | 交流群:1361692 7710545
本站部分带宽由:华夏名网武汉IDC数据中心 赞助[排名不分先后] Powered By 零度软件园
本站软件均来源于网络,仅供学习所用。若侵犯了你的权益,请立即通知我们,我们将第一时间删除!