2017-05-31 75 views
0

我嘗試以下:如何在JavaScript中發生錯誤後繼續處理代碼?

window.onerror = function (msg, url, line, col, err) { 
    return true 
} 

它僅防止在控制檯中所示的誤差,然而,代碼停止被處理。

我希望瀏覽器忽略錯誤並繼續處理下一行,所以在下面的代碼:

alert(IDontExist); 
alert("Hello"); 

第二警報應彈出,雖然之前它的ReferenceError。

更新1:try...catch不是這裏的方法,因爲有問題的代碼將是外部的。因此,代碼更像是:

內嵌HTML:

<script src="problematic.js"></script> 

problematic.js

alert(UndefinedVariable); 
alert("I am valid JS"); 

在這裏,我想 「我是JS有效」,彈出。

+1

重寫'window.error'裏面對你沒有好處。遇到錯誤時,它會打破正常的工作流程,然後使用'window.error',您將打印它。正確的方法是將任何這樣的代碼放入'try ... catch'中。 – Rajesh

+1

通過使用try/catch? – Li357

+0

Rajesh Andrew Li不幸的是'try ... catch'在這裏不起作用,因爲有問題的代碼是外部不內聯的。 – Russel

回答

0

嘗試包裝你的問題的功能try-catch

try{ 
    //Here you put the code that it could crash 
    console.log("Trying to execute the function"); 
    problematicFunction(); 
    //If an error is found, the code will go to catch and stop the try execution 
    console.log("I will never be executed! :c"); 
} catch(e){ 
    //And here you put what to do in case that you have an error 
    console.log("Hey i'm a cool error!\n" + e); 
} 
console.log("Guess what? I still working :D"); 
+0

有問題的代碼將是外部的,請查看更新。 – Russel

相關問題