在代碼的運行過程中,問題時有發(fā)生;如何優(yōu)雅的處理的這些錯誤,現(xiàn)的很重要。總體來說問題分為2大類:
系統(tǒng)級錯誤,簡稱為error,如語法錯誤;應用級錯誤簡稱為exception,如用戶輸入的數(shù)值不合法等。如何當
前代碼不能處理此問題,則應該把此問題從當前運行環(huán)境中跳出,并把它交給上一級環(huán)境處理。這就用到了
try{}catch(){}異常處理。
問題的相關信息被封裝到一個對象里。在javascript中,常用Error對象來保存有關錯誤的信息。
為了區(qū)別系統(tǒng)級錯誤和應用級錯誤,給Error錯誤增加type屬性(error/exception)。
示例代碼如下:
<script language="javascript">
function errorTest(){
try{
var s;
alert(s.toString());
}catch(e){
var error=new Error();
error["type"]="error";
error["number"]="110";
error["description"]=e["description"]
throw error;
}
}
function exceptionTest(i){
try{
if(parseInt(i)>0)
{
var exception=new Error();
exception["description"]="不能大于0";
throw exception;
}
}catch(e){
var exception=new Error();
exception["description"]=e["description"];
exception["type"]="exception";
exception["number"]="120";
throw exception;
}
}
function test1(){
try{
errorTest();
}catch(e){
if(e["type"]=="error"){
alert("系統(tǒng)級錯誤!");
}else{
alert("應用級錯誤!");
}
}
}
function test2(){
try{
exceptionTest(1);
}catch(e){
if(e["type"]=="error"){
alert("系統(tǒng)級錯誤!");
}else{
alert("應用級錯誤!");
}
}
}
test1();
test2();
</script>
以上代碼比較簡單,但是在代碼比較復雜的情況下,可以根據(jù)具體情況完善。用此異常框架處理起來流程比較清晰。