1. 程式人生 > >try catch 小結 , node的回調callback裏不能捕獲異常 , 不能被v8優化(現在能了),

try catch 小結 , node的回調callback裏不能捕獲異常 , 不能被v8優化(現在能了),

容易 sin ejs called ack tro 崩潰 span 檢查

《深入淺出Nodejs》時,在第四章 - 異步編程中作者樸靈曾提到,異步編程的難點之一是異常處理,書中描述"嘗試對異步方法進行try/catch操作只能捕獲當次事件循環內的異常,對call back執行時拋出的異常將無能為力"。

//test.js
var test = undefined;
try{
    var f1 = function(){
         console.log(test.toString());  
    }
}
catch(e){
    console.log(error..);
}
//assume somewhere f1() will be called as an call back function
f1();

這裏模仿f1函數是做為call back(回調)函數傳遞給其他函數,在其他函數執行過程中執行call back的函數。從代碼表面來看,很容易認為如果Line 7,

1 console.log(test.toString());

  如果這行code發生異常,會自然認為其會被try catch捕獲到,並不會引起進程的Crash。但其實,運行結果是:

  技術分享

  運行錯誤,Line 11的錯誤並沒有打印,說明在程序中錯誤沒有被Try Catch。而Nodejs作為單進程單線程程序,將會引起進程的Crash(崩潰)!

  ------------------------------------------------------------------------------------------------------------------------

  因此,在進行異步編程時,個人覺得:

  要考慮到call back函數可能產生的錯誤,增加類型檢查代碼或在Call back被真正執行的地方增加Try cach等,避免異常未能被捕獲導致進程Crash

  ------------------------------------------------------------------------------------------------------------------------

  如本例,可修改如下,

1 if(typeof(test) != ‘undefined‘){
2     console.log(test.toString());  
3 }

  或者

1 console.log(test? test.toString() : ‘[undefine]‘);

  或者

try{
    f1();
}
catch(e)
{
    console.log(new error..);
}

try catch 小結 , node的回調callback裏不能捕獲異常 , 不能被v8優化(現在能了),