2015-09-06 59 views
0

我有一些這樣的代碼的打擊, 如果擲1,顯示將不能在追趕的NodeJS錯誤和MongoDB

catch in main 
throw 1 

如果擲2,顯示將

catch in test 
throw 2 

但如果我想要這樣的顯示,

catch in test 
throw 2 
catch in main 
throw 2 

我該怎麼辦?

function test(database) 
{ 
    if(1) throw 'throw 1'; //if throw at here, 'catch in main' will display 
    var col=database.collection('profiles'); 
    col.findOne({"oo" : 'xx'}) 
    .then(function(doc){ 
     throw 'throw 2'; //if throw at here, 'catch in main' will [NOT] display 
    }) 
    .catch(function(e){ 
    console.log('catch in test'); 
    console.log(e); 
    throw e; 
    }); 
} 

MongoClient.connect(url, function(err, database) { 
    try{ 
    test(database); 
    }catch(e){ 
    console.log('catch in main'); //if throw 2, this line will [NOT] run 
    console.log(e); 
    } 
}); 

回答

0

當您使用的承諾(和你在這種情況下是),幾乎沒有使用try-catch包裹的客戶端代碼。你應該做的是1)從test函數返回一個承諾; 2)用catch方法訂閱回執。一種可能的方法:

// in test() 
return col.findOne({"oo" : 'xx'}) 
.then(function(doc){ 
    throw 'throw 2'; //if throw at here, 'catch in main' will [NOT] display 
}) 
.catch(function(e){ 
    console.log('catch in test'); 
    console.log(e); 
    throw e; // 
}); 

// in main: 
function handleError(e) { 
    console.log('catch in main'); 
    console.log(e); 
} 

// ... 
try { 
    test(database).catch(handleError); 
} catch(e) { 
    handleError(e); 
} 

順便說一句,在我看來,你的第一個例子(在你自己的代碼拋)是人爲的(僅推出,使一般的作品肯定try-catch),並在實際情況下,它只有可能以錯誤結束的數據庫函數。如果我是正確的,你可能想完全擺脫try-catch塊:承諾.catch處理程序就足夠了。