LoginSignup
0
0

More than 5 years have passed since last update.

Node.js にて Promise オブジェクトの中で例外が発生したときの挙動を確認する

Last updated at Posted at 2019-04-20

概要

  • Promise オブジェクトの中で例外が発生したときの挙動を確認する
  • await を付けて呼び出して try catch で捕捉するパターンを試す
  • Promise.catch で捕捉するパターンを試す

サンプルコード

p.js
// Promise オブジェクトを返す関数
function foo() {
  // Promise を返す
  return new Promise(function(resolve, reject) {
    // Promise の中で例外を発生させる
    throw new Error('例外発生');
  });
}

async function bar() {

  try {
    await foo();
  } catch (e) {
    console.log('await つけて呼び出して try catch で捕捉');
    console.log(e);
  }
  console.log('');

  foo()
  .then(function(r){
  })
  .catch(function(e){
    console.log('Promise.catch で捕捉');
    console.log(e);
  });
  console.log('');
}

bar();

実行結果

Proimise 関数内で例外が発生した場合、呼び出し元で捕捉する必要があることがわかる。

$ node p.js 
await つけて呼び出して try catch で捕捉
Error: 例外発生
    at /Users/me/hoge/p.js:6:11
    at new Promise (<anonymous>)
    at foo (/Users/me/hoge/p.js:4:10)
    at bar (/Users/me/hoge/p.js:13:11)
    at Object.<anonymous> (/Users/me/hoge/p.js:30:1)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)


Promise.catch で捕捉
Error: 例外発生
    at /Users/me/hoge/p.js:6:11
    at new Promise (<anonymous>)
    at foo (/Users/me/hoge/p.js:4:10)
    at bar (/Users/me/hoge/p.js:20:3)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:757:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

今回の環境

$ node --version
v10.15.3

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.14.4
BuildVersion:   18E226

参考資料

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0