如何在 node-postgres 中捕获 client.connect()?

Hen*_*nry 4 postgresql error-handling node.js node-postgres

try/catch 不适用于 client.connect():

const { Pool, Client } = require('pg')
try {
  const client = new Client(config)
  client.connect()
} catch (er) {
  console.log('error')
}
Run Code Online (Sandbox Code Playgroud)

错误:

UnhandledPromiseRejectionWarning: error: password authentication failed for user '...'
Run Code Online (Sandbox Code Playgroud)

如何将异步更改connect()为 try/catch 同步?

Mur*_*nik 5

connect()没有回调函数会返回一个承诺,您可以将该.catch方法应用于:

client
  .connect()
  .then(() => console.log('connected'))
  .catch(err => console.error('connection error', err.stack))
Run Code Online (Sandbox Code Playgroud)