2015-09-06 4 views
0

J'ai un code comme coup, si un jet 1, l'affichage devientne peut pas attraper erreur dans nodejs et MongoDB

catch in main 
throw 1 

si un jet 2, l'affichage sera

catch in test 
throw 2 

mais si Je veux l'affichage comme ceci,

catch in test 
throw 2 
catch in main 
throw 2 

comment puis-je faire?

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); 
    } 
}); 

Répondre

0

Lorsque vous utilisez des promesses (et vous êtes dans ce cas), il y a peu d'emballage utilisé le code client dans try-catch. Ce que vous devez faire est 1) renvoyer une promesse de test fonction; 2) s'inscrire sur la promesse de rejet 'rejeter avec la méthode catch. Une approche possible:

// 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); 
} 

Par ailleurs, il me semble que votre premier exemple (avec lancer dans votre propre code) est artificielle (introduite seulement pour se assurer try-catch dans les ouvrages généraux), et dans votre cas réel, il est Seules les fonctions DB pouvant se terminer par une erreur. Si je me trompe, vous voudrez peut-être vous débarrasser complètement de ce bloc try-catch: la promesse .catch sera suffisante.