如果出现 pg 错误,express 服务器将关闭

express server shutting down if there is a pg error

我有一个附加到 pg 数据库的 express 应用程序。我正在处理错误。我希望将 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 (, , , , )', [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`)
        })
       
  }

仅供参考,您的服务器可能正在关闭,因为您在 console.error(err.message) 中引用了 err.message,但变量名称是 error,而不是 err

您还需要将错误响应发送回客户端。您的服务器收到的每个 http 请求都需要发送某种类型的响应:

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 (, , , , )', [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`)
        })
       
  }

您的服务器正在关闭,因为您的回调函数正在引用 error 而不是 err

试试下面的代码:

 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 (, , , , )', [name, email, body, tag, subject ], (err, results) => {
              if (err) {
                return console.error(err.message);
              } else
              console.log("get to Success contact")
              response.status(200).send(`Inbox Added`)
            })
           
      }