LoginSignup
3
0

More than 5 years have passed since last update.

nodejsのpgでcatchを書く方法

Last updated at Posted at 2018-09-12

これがベスト。以下、例外をキャッチする所と例外をtoStringしたメッセージ

いい例。catchした中でnew ErrorをPromise.rejectで囲んでreturnする。この書き方だと例外で自分のコードのどこでエラーが起きたのか分かる。

await this.dbClient.query("example;").catch(e => Promise.reject(new Error(e)) );
 Error: error: syntax error at or near ";"
    at dbClient.query.catch.e (自分のコード.js:44:65)
    at process._tickCallback (internal/process/next_tick.js:68:7)

駄目な例1。catchした例外を再度new Errorでインスタンスを作りthrowする。最初はこれでいいと思ったけど、throwはよくない。

await this.dbClient.query("example;").catch(e => { throw new Error(e) });
 Error: error: syntax error at or near ";"
    at dbClient.query.catch.e (自分のコード.js:44:65)
    at process._tickCallback (internal/process/next_tick.js:68:7)

駄目な例2。これはそもそもcatchの意味がない。スタックトレースがpgのモジュールから始まっていて、自分のコードのどこで例外が起きたのか分からない。

await this.dbClient.query("example;").catch(e => { throw e });
 error: syntax error at or near ";"
   at Connection.parseE (node_modules\pg\lib\connection.js:553:11)
   at Connection.parseMessage (node_modules\pg\lib\connection.js:378:19)
   at Socket.<anonymous> (node_modules\pg\lib\connection.js:119:22)
   at Socket.emit (events.js:182:13)
   at addChunk (_stream_readable.js:283:12)
   at readableAddChunk (_stream_readable.js:264:11)
   at Socket.Readable.push (_stream_readable.js:219:10)
   at TCP.onread (net.js:639:20)

駄目な例1についてもう少し。

http://azu.github.io/promises-book/#not-throw-use-reject には以下の記述がある。

image.png

Promiseオブジェクトの状態がrejectedかどうかという意味。具体的な違いは、上記ページに書いてあるとおりChromeのdevtoolのpause on caught exceptionで止まるかどうかの違いがあるらしい。

catchした後は違いがない感じかな

3
0
0

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
3
0