首页 > 解决方案 > 如何在 Node/Express 的客户端中正确呈现服务器端错误?

问题描述

我已经设置了一个简单的 Node/Express 服务,可以为数据库创建新的书签。

在我的书签架构中,其中一个字段 url 具有验证。当您尝试在没有正确验证的情况下创建新书签时,它会引发错误和消息。

例如,如果您没有为请求提供 url,那么它将抛出一条消息Please provide a url.

POST 请求创建新书签的路径:

app.post(
    '/api/bookmarks',
    (req, res) => {
      const { url, tags } = req.body;

      const bookmark = new Bookmark({
        url,
        tags
      });

      bookmark.save()
        .then(res => {
          res.send(result)
        })
        .catch(error => {
          console.log("err:", error);
          res.status(400).send(error)
        });
    }
  );

我的书签架构是什么样的:

const bookmarkSchema = new Schema({
  url: {
    type: String,
    required: [true, "Please provide a URL."],
    match: [urlRegex, "Your URL is invalid. Please make sure to add www."]
  },
  tags: [String]
});

当我在前端客户端(例如通过React )上进行 API 调用时,我能够捕捉到错误和后续消息Please provide a URL.err.response.data.errors.url.message

axios.post('http://localhost:5000/api/bookmarks', { tags: ["banana", "orange"] })
  .then(result => console.log('Result:', result.data))
  .catch(err => console.log('Error:', err.response.data.errors.url.message));

我在想什么 - 有没有更好的方法在这里呈现错误?在客户端处理错误会更好吗?

我对错误处理很陌生,所以想知道什么是最佳实践。

谢谢!

标签: node.jsexpresserror-handlinghttprequest

解决方案


像这样的东西。所以你不必在模式中检查它。

app.post(
    '/api/bookmarks',
    (req, res) => {
      const { url, tags } = req.body;
      if (!url) {
        res.status(400).send({error: "URL is missing"})
        return;
      }
      if (!url.match(urlRegex) {
        res.status(400).send({error: "URL is not valid"})
        return;
      }
      const bookmark = new Bookmark({
        url,
        tags
      });

      bookmark.save()
        .then(res => {
          res.send(result)
        })
        .catch(error => {
          console.log("err:", error);
          res.status(500)
        });
    }
  );

将服务器端错误发送到前端是一种不好的做法。这是一种泄露数据库/后端信息的简单方法。您应该发送自己的字符串消息而不是捕获的错误。


推荐阅读