繁体   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