首页 > 解决方案 > 如果出现 pg 错误,表示服务器关闭

问题描述

我有一个快速应用程序附加到 pg 数据库。我正在处理错误。我希望将 pg 错误消息发送到前端,以便用户知道为什么此表单没有发送。现在,如果我向这个端点发送违反我的数据库约束的信息,它会关闭我的服务器。

我认为这与我如何处理错误有关,但我是新手,对如何处理这个问题有点困惑。

这是我的代码:快速路线:

app.post('/api/inbox', inbox.createInbox)

创建收件箱功能:

 const createInbox = (request, response) => {
    const { name, email, body, tag, subject } = request.body
      console.log("request body", request.body)
        pool.query('INSERT INTO inbox (name, email, body, tag, subject ) VALUES ($1, $2, $3, $4, $5)', [name, email, body, tag, subject ], (error, results) => {
          if (error) {
            return console.error(err.message);
          }
          console.log("get to Success  contact")
          response.status(200).send(`Inbox Added`)
        })
       
  }

标签: javascriptexpressnode-postgres

解决方案


FYI, your server was probably shutting down because you were referencing err.message in console.error(err.message), but the variable name is error, not err.

You also need to send an error response back to the client. Every http request your server receives needs to send some type of response:

const createInbox = (request, response) => {
    const { name, email, body, tag, subject } = request.body
      console.log("request body", request.body)
        pool.query('INSERT INTO inbox (name, email, body, tag, subject ) VALUES ($1, $2, $3, $4, $5)', [name, email, body, tag, subject ], (error, results) => {
          if (error) {
            console.error(error.message);                // log correct variable
            response.status(500).send(error.message);    // send error response
            return;
          }
          console.log("get to Success  contact")
          response.status(200).send(`Inbox Added`)
        })
       
  }

推荐阅读