2016-06-01 8 views
0

catchブロック内の約束からスローされたエラーをどのように処理すればよいでしょうか?例えばNodeJs try catchブロックで約束エラーを処理しています

try { 

    // some other functions/code that can also throw error 

    var promise = // a service that returns new Promise() object 

    promise.then(function(data) { 
     //some business logic 
    }, function(err) { 
     throw new Error(err); // never gets caught in catch block 
    }); 
} catch(error) { 
    // do something with error 
    console.log(error); 
} 

1)約束からスローのtry catchブロックでエラーを処理することが可能ですか?

2)一般的なエラーを処理するにはいくつかの方法がありますか?

答えて

3

プロミスは、非同期で動作し、ここにあるcatchブロックの範囲外で実行されます。

promise 
.then(function(data) { 
    //some business logic 
    return anotherPromise; 
}) 
.then(function(data) { 
    //some other business logic 
}) 
// this keeps chaining as long as needed 
.catch(function(err) { 
    // You will get any thrown errors by any of the 
    // chained 'then's here. 
    // Deal with them here! 
}); 

これは推奨される方法です - 彼らはcatchの独自のバージョンを持っている理由です。

+1

さらに遅くすると、後でチェーンを中止する必要がないように、キャッチで回復することができます(たとえば、サービスで「.catch」でAJAX要求を再試行します)。 – ste2425

関連する問題