2013-10-31 59 views
-1

我試圖用錯誤處理try/catch來捕捉Ajax錯誤,但它不工作。這裏是我的代碼:Javascript錯誤處理不起作用

var ajaxrequest=null 
if (window.ActiveXObject){ 
try { 
    ajaxrequest=new ActiveXObject("Msxml2.XMLHTTP") 
} 
catch { 
    try{ 
    ajaxrequest=new ActiveXObject("Microsoft.XMLHTTP") 
    } //end inner try 
    catch { 
    alert("NOT WORKING!!") 
    } //end inner catch 
} //end outer catch 
} 
else if (window.XMLHttpRequest) // if Mozilla, Safari etc 
ajaxrequest=new XMLHttpRequest() 

ajaxrequest.open('GET', 'inventory.php', true) //do something with request 

我做錯了什麼?

+2

也許它只是不會拋出一個例外...... – 2013-10-31 19:50:38

回答

1

您錯過了要捕捉的參數。它應該是catch(ex)。以下是修復:

if (window.ActiveXObject){ 
try { 
    ajaxrequest=new ActiveXObject("Msxml2.XMLHTTP") 
} 
catch (ex){ 
    try{ 
    ajaxrequest=new ActiveXObject("Microsoft.XMLHTTP") 
    } //end inner try 
    catch (ex){ 
    alert("NOT WORKING!!") 
    } //end inner catch 
} //end outer catch 
} 
+0

就是這樣!我真的需要多睡一會兒!謝謝! – devXen

0

使用catch子句w/o任何參數導致SyntaxError: Unexpected token {。捕捉異常的正確方法是這樣的:

try { 
    // some code which probably causes exception 
} catch(e) { 
    // do something with the exception 
} 

檢查出exception handling in JavaScript的文檔。