1

https://node-postgres.com/guides/async-express上的文档给出了以下示例:

const { Pool } = require('pg')
const pool = new Pool()
module.exports = {
  query: (text, params) => pool.query(text, params),
}

我的数据库代码实际上是相同的,但添加了一些日志记录:

const { Pool } = require('pg')

var config = {
  user: process.env.DB_USER,
  database: process.env.DB,
  password: process.env.DB_PASSWORD,
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  max: 10,
  idleTimeoutMillis: 30000,
};

const pool = new Pool(config);
module.exports = {
  query: (text, params) => {
    console.log(`sql: ${text}, params: ${params}`);
    return pool.query(text, params);
  }
}

当使用以下方法调用时,这可以正常工作:

const result = await db.query('SELECT * FROM users WHERE email = $1 AND password = $2;', 
                              [req.body.email, req.body.password]);

当我在 SQL 中出错时,我会收到警告:

(node:6345) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:6345) [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.
POST /verify - - ms - -
post /verify
(node:6345) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined
    at router.post (/home/fadedbee/myapp/routes/index.js:93:58)
    ...
    at router (/home/fadedbee/myapp/node_modules/express/lib/router/index.js:47:12)
(node:6345) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.是我担心的。

我应该如何更改我的数据库代码来解决这个问题?

4

3 回答 3

2

selfagencies回答没有功能上的差异,但关于“大量噪音”......重复的错误处理代码可以被提取到加载您的处理程序并执行任何常见请求/响应工作的帮助程序中。

async function myHandler(req, res){ 
  const query = 'SELECT * FROM users WHERE email = $1 AND password = $2;'
  return db.query(query, [ req.body.email, req.body.password ]);
})

function loadRoute(handlerFunction){
  return async function routeLoaderHelper(req, res, next){
    try {
      const res = await handlerFunction(req, res, next)
      // or templatey handling can go here too
      res.json({ data: res })
    }
    catch (error) {
      console.error(error)
      res.status(error.status || 500).json({ error })
    }
  }
}

app.post('/whatever', loadRoute(myHandler))

或使用koa,这是“异步”快递。

于 2021-02-17T08:42:31.647 回答
1

您需要将您的包裹awaittry/catch块中并处理错误。

const query = 'SELECT * FROM users WHERE email = $1 AND password = $2;';

try {
  const result = await db.query(query, [req.body.email, req.body.password]);
  
  // do something with result
} catch(error) {
  console.error(error)
}
于 2021-02-17T06:36:13.710 回答
0

跑步:

npm install express-promise-router --save

然后将我的 routes/index.js 的顶部从:

const express = require('express');
const router = express.Router();

至:

const router = require("express-promise-router")();

很好地解决了这个问题。我现在得到一个错误页面,在开发过程中带有堆栈跟踪。

我不需要添加任何try {块或包装函数。

于 2021-02-17T19:37:51.390 回答