【问题标题】:Error handling in node js backend节点 js 后端中的错误处理
【发布时间】:2018-07-26 00:31:08
【问题描述】:

我正在使用 node.js 后端,但在错误处理方面遇到了一些问题。

在后端,我使用 express 进行路由。我从前端收到一个 ajax 帖子,其中包含一个数组和一些数据。此数据应保存在数据库中。如果通过将数据添加到数据库中出现错误,我会在后端收到错误消息,但我也想向前端发送一条消息。我一直在尝试错误,但在前端我总是得到“成功”。 这是我到现在为止的代码。

后端:

router.post('/tagging', function(req, res) {
  var taggedData = req.body;

  var actions = taggedData.map(element => {
    addTaggedData.addTaggedData(element)
      .then(function(result) {
        return result;
      })
      .catch(function(err) {
        if (err.code == "ER_NO_SUCH_TABLE") {
          console.log("Tagged data contains unknown project name");
          res.send("ER_NO_SUCH_TABLE");
        } else {
          res.send(err);
        }
      })
  });
  Promise.all(actions)
    .then(
      res.send("Successful")
    )
    .catch(function(err) {
      if (err.code == "ER_NO_SUCH_TABLE") {
        console.log("Tagged data contains unknown project name");
        res.send("ER_NO_SUCH_TABLE");
      } else {
        res.send(err);
      }
    });
})

前端ajax调用:

function postTaggedData(taggedData) {
$.ajax({
    url: server_connection.url + '/tagging',
    type: 'POST',
    encoding: "UTF-8",
    contentType: 'application/json',
    data: JSON.stringify(taggedData),
    success: function(data) {
        if (data === "Successful") {
            console.log("Tagged Data successfully send to server");
        }else if(data == "ER_NO_SUCH_TABLE"){
            alert("Unknown project");
        } else {
            alert(data);
        }
    },
    error: function(xhr, status, error) {
        if(error == "Internal Server Error"){
            alert("There is an error with the server");
        }else if(error == "ER_NO_SUCH_TABLE"){
            alert("Unknown project");
        }else{
            alert("There was an error while sending the Tagged Data to the server");
            console.log(xhr, "Status: ", status, error);
        }

    }
})

}

【问题讨论】:

  • 在 addTaggedData.addTaggedData(element) 之前缺少返回语句

标签: node.js ajax error-handling promise


【解决方案1】:

即使您将错误作为响应发送,express 也不知道这是一个错误,因此它使用状态码 200 发送它,这意味着 OK,因此前端认为响应成功。

尝试设置非正常状态,然后发送如下错误:res.status(404).send(err)。其中404 是“Not Found”的状态码

你可以找到更多关于状态码here

你可以找到更多关于快速错误处理here

【讨论】:

    猜你喜欢
    • 2022-12-10
    • 2016-06-12
    • 2021-11-15
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2018-08-08
    相关资源
    最近更新 更多