簡體   English   中英

Axios + Sequelize ValidationError =承諾捕獲塊中沒有請求或響應對象? 如何處理?

[英]Axios + Sequelize ValidationError = no request or response objects in promise catch block? How to handle?

通常,我有一些類似以下內容的Axios調用:

api.post('/users/add', (req, res, next) => {
  Users.create(req.body).then(userResult => {
    // misc code here
    return res.json(userResult)
  }).catch((err, req, res, next) => {
    if (err) {
      // handle the error by sending to the application error handler
      next(err);
    }
  });
});

我遇到的問題是,如果錯誤是Sequelize驗證錯誤,則req,res和next似乎不存在。 因此,我在IF中添加了一個檢查,如下所示:

if (err) {
  if (err instanceof Sequelize.ValidationError) {
    // i've tried a lot here and am stuck as to what to do
  } else {
    // handle other errors
  }
}

一旦進入該內部IF,我就可以很好地檢查該錯誤,但是我不知道該怎么做才能將響應返回給調用瀏覽器。 我也不能調用next()並將錯誤冒泡到我的常規錯誤處理程序中,因為它無法識別next()。 如果可以的話,我通常在req或res中使用的項目不可用。

我遍歷了Sequelize網站上的所有文檔,仔細研究了問題隊列,在stackoverflow上進行了搜索,似乎找不到相同的問題。 因此,我認為解決方案很簡單,僅是我所知。 請賜教。 我該如何使它冒泡到我的常規錯誤處理程序,或者從此處向瀏覽器返回響應?

您不應該在catch中重新定義reqresnext 它們可以從父作用域訪問,但是通過將它們包含在catch中,它們將是未定義的,因為then / catch僅具有單個參數。

/* create a POST route. for /users/add requests it will 
   call a function passing in req, res, next() */
api.post('/users/add', (req, res, next) => { // this syntax creates an "arrow function"
  /* note that it's probably a bad idea to just 
     pass in the request.body without sanitizing */
  return Users.create(req.body)    // call Sequelize and get a Promise
    .then((userResult) => {        // success, userResult will be the new user
      return res.json(userResult); // use res.json() to send to client
    })
    .catch((err) => {              // create failed
      return next(err);            // pass the err along to next()
    });
});

如果要使用async/await編寫相同的代碼,則可以使用同步語法編寫異步代碼。 添加async該功能將自動返回Promise。 使用await將等待Promise解決(或引發錯誤),而不會陷入困境(在這種情況下為用戶創建的結果)。

api.post('/users/add', async (req, res, next) => {
  try {
    const user = await Users.create(req.body);
    return res.json(userResult);
  } catch (err) {
    return next(err);
  }
});

暫無
暫無

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

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