首页 > 解决方案 > 异常处理不适用于 PG npm 包

问题描述

我使用数据库凭据安装"pg": "^8.0.2"并创建了该文件。database.js但无论出现什么问题,它都不会进入catch block显示错误。相反,它总是记录connected to the database. 谁能指出我做错了什么。谢谢你!

数据库.js

const Pool = require('pg').Pool;

  const pool = new Pool({
    user: 'roothjk',
    host: 'localhost',
    database: 'sf',
    password: 'admin',
    port: 5432
  });
  try {
    pool.connect()
    console.log('connected to the db');

  } catch (e) {
    console.log('Error connecting to db');

  }

标签: node.jspostgresqlexpress

解决方案


connect返回 a Promise,然后转到下一条语句。相反,您应该使用thenandcath 方法

pool.connect()
    .then(c => console.log('connected to the db'))
    .catch(e => console.log('Error connecting to db'));

推荐阅读