簡體   English   中英

錯誤處理:如何在我的前端接收來自我的后端的錯誤消息?

[英]Error handling: How to receive error message from my backend on my frontend?

我正在構建我的第一個全棧應用程序,並且我在后端的錯誤處理方面遇到了問題,我也不知道如何在我的前端接收此錯誤消息。

這是我的應用程序的工作方式:(我正在使用 nodejs、express.js、mongodb 並做出反應)

 // 1. I got a form where user provide some data. 
 // 2. Redux action creator is sending this data to my API.
 // 3. Basing on this data, my API is fetching other API for some information.
 // 4. And the response is pushed to my data base, and then send back to my reducer, and it's in my store. 

問題是,在我將響應推送到我的數據庫之前,我想檢查這個項目是否存在於我在后端獲取的 API 中,如果不存在,那么我想接收這種消息,並將其顯示給我的表單下方的用戶。

這是我在前端的動作創建者:

export const addTransaction = (transaction) => async (dispatch) => {
  try {
    const { data } = await api.addTransaction(transaction);

    dispatch({
      type: ADD_TRANSACTION,
      payload: data
    });
  } catch (error) {
    console.log(error.message);
  };
};

這是我的后端 controller:

export const addTransaction = async (req, res) => {
  const transaction= req.body

  const myUpdatedTransaction = {
    ...transaction,
    someOther: "fields"
  };

  const requestOptions = {/*GET, url, api_key, etc. */},

// here is where I'm trying to handle this case

  await request(requestOptions).then( async (resolve) => {

    if(resolve) { 

      const newTransaction = new TransactionItem(myUpdatedTransaction) 
      
      await newTransaction.save();

      res.status(201).json(newTransaction);

      return;
    }

  }, (err) => {
    /******** And here where I don't know how to deal with this *******/
    console.log('error ----->');

    if(err) {
      res.status(409).json({ message: 'Check if the ticker is correct.'});
      console.log('409');

      return;
    }

  });

};

如果有人可以分享一些鏈接,我將不勝感激,我可以在其中了解有關錯誤處理的更多信息。

好吧,看起來你混淆了兩個概念。

https://www.smashingmagazine.com/2020/11/comparison-async-await-versus-then-catch/

export const addTransaction = async (req, res) => {
  const transaction= req.body

  const myUpdatedTransaction = {
    ...transaction,
    someOther: "fields"
  };

  const requestOptions = {/*GET, url, api_key, etc. */},

// here is where I'm trying to handle this case

try{
  const resolve = await request(requestOptions);
  
  if(resolve) { 

      const newTransaction = new TransactionItem(myUpdatedTransaction) 
      
      await newTransaction.save();

      res.status(201).json(newTransaction);

      return;
  }
}catch(err){
    /******** And here where I don't know how to deal with this *******/
    console.log('error ----->');

    if(err) {
      res.status(409).json({ message: 'Check if the ticker is correct.'});
      console.log('409');

      return;
    }

}

};

暫無
暫無

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

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