2017-10-05 7 views
0

async関数内でスローされたエラーをどのように捕捉できますか?以下の私の例のように:nodejs - より深いレベルでエラーをキャッチ

I)の作業例(エラー捕捉可能)

(async() => { 
    try { 
    // do some await functions 

    throw new Error("error1") 
    } 
    catch(e) { 
    console.log(e) 
    } 
})() 

コンソール

Error: error1 
    at __dirname (/home/test.js:25:11) 
    at Object.<anonymous> (/home/quan/nodejs/IoT/test.js:30:3) 
    at Module._compile (module.js:624:30) 
    at Object.Module._extensions..js (module.js:635:10) 
    at Module.load (module.js:545:32) 
    at tryModuleLoad (module.js:508:12) 
    at Function.Module._load (module.js:500:3) 
    at Function.Module.runMain (module.js:665:10) 
    at startup (bootstrap_node.js:201:16) 
    at bootstrap_node.js:626:3 

II)しかし、私はasynctry-catch外に置けば、例外は次のように、キャッチできないとなり以下:

try { 
    (async() => { 
    throw new Error("error1") 
    })() 
} 
catch(e) { 
    console.log(e) 
} 

コンソール:

(node:3494) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: error1 

(node:3494) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 

asyncから派生したエラーをIIで示したようにキャッチする方法はありますか?

多くの場合、switch-caseが含まれており、switch-casetry-catchを処理したくないコードを簡略化するためにこの質問をする必要があります。あなたが約束鎖の末端にキャッチを追加し、この問題を解決するための約束を使用することができます

よろしく、

答えて

0

は非同期エラーをキャッチするのに役立ちます。

function resolveAfter2Seconds(x) { 
     return new Promise(resolve => { 
      if(x === 'Error'){ 
       throw Error('My error') 
      } 

      setTimeout(() => { 
      resolve(x); 

      }, 2000); 
     }).catch(function (e){ 
      console.log('error-------------------', e) 
     }); 
     } 

     async function add1(x) { 
     const a = await resolveAfter2Seconds('success'); 
     const b = await resolveAfter2Seconds('Error'); 
     return x + a + b; 
     } 

     add1(); 
関連する問題