簡體   English   中英

如何在Node / Express的客戶端中正確呈現服務器端錯誤?

[英]How to properly render server-side errors in the client for Node/Express?

我已經設置了一個簡單的Node / Express服務,該服務為數據庫創建了新的書簽。

在我的書簽架構中,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]
});

當我在前端客戶端上進行API調用時(例如通過React),我能夠捕獲錯誤和后續消息( 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));

我在想什么-是否有更好的方法來呈現錯誤? 會更好地處理客戶端中的錯誤嗎?

我對錯誤處理還很陌生,所以想知道什么是最佳實踐。

謝謝!

這樣的事情。 因此,您不必在模式中進行檢查。

 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) }); } ); 

將服務器端錯誤發送到前端是一種不好的做法。 這是泄漏有關數據庫/后端信息的簡單方法。 您應該發送自己的字符串消息,而不是捕獲的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM