2012-05-30 41 views
7

基本上,爲什麼這個異常不被捕獲?異步javascript中引發的異常未捕獲

var http = require('http'), 
    options = { 
     host: 'www.crash-boom-bang-please.com', 
     port: 80, 
     method: 'GET' 
    }; 

try { 
    var req = http.request(options, function(res) { 
    res.setEncoding('utf8'); 
    res.on('data', function (chunk) { 
     console.log('BODY: ' + chunk); 
    }); 
    }); 

    req.on('error', function(e) { 
    throw new Error("Oh noes"); 
    }); 
    req.end(); 
} catch(_error) { 
    console.log("Caught the error"); 
} 

一些人認爲需要與事件發射器或回調(ERR)來處理這些錯誤(具有ERR回調,數據簽名是不是我已經習慣了)

什麼是最好的該怎麼辦?

回答

8

當你拋出錯誤時,try {}塊已經很長時間了,因爲回調是在try/catch之外異步調用的。所以你不能抓住它。

在錯誤回調函數內發生錯誤時,請執行任何您想要的操作。

5

從節點版本0.8起,您可以將例外限制爲domains。您可以限制異常某個域,並趕上他們在這個範圍

如果你有興趣,我寫了一個小功能,這裏捕獲異步異常:Javascript Asynchronous Exception Handling with node.js。我喜歡的一些反饋這將讓你執行以下操作:

var http = require('http'), 
    options = { 
     host: 'www.crash-boom-bang-please.com', 
     port: 80, 
     method: 'GET' 
    }; 

atry(function(){ 
    var req = http.request(options, function(res) { 
    res.setEncoding('utf8'); 
    res.on('data', function (chunk) { 
     console.log('BODY: ' + chunk); 
    }); 
    }); 

    req.on('error', function(e) { 
    throw new Error("Oh noes"); 
    }); 
    req.end(); 
}).catch(function(_error) { 
    console.log("Caught the error"); 
}); 
+0

哇,真的很好!我分享這個。 – changelog

0

JavaScript沒有只是功能範圍,的try-catch也是塊作用域。這就是原因。