简体   繁体   English

Axios + Sequelize ValidationError =承诺捕获块中没有请求或响应对象? 如何处理?

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

Typically, I have Axios calls that look something like this: 通常,我有一些类似以下内容的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);
    }
  });
});

The problem I'm having is that req, res, and next do not seem to exist if the error is a Sequelize validation error. 我遇到的问题是,如果错误是Sequelize验证错误,则req,res和next似乎不存在。 So I add a check inside the IF like this: 因此,我在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
  }
}

I can inspect the error just fine once I'm in that inner IF, but I don't know what to do to get a response back out to the calling browser. 一旦进入该内部IF,我就可以很好地检查该错误,但是我不知道该怎么做才能将响应返回给调用浏览器。 I also can't call next() and bubble up the error to my regular error handler since it doesn't recognize next(). 我也不能调用next()并将错误冒泡到我的常规错误处理程序中,因为它无法识别next()。 And if I could, the items I usually use from req or res aren't available. 如果可以的话,我通常在req或res中使用的项目不可用。

I've gone over all of the documentation on the Sequelize website, pored over the issue queue, searched here on stackoverflow, and can't seem to find the same problem. 我遍历了Sequelize网站上的所有文档,仔细研究了问题队列,在stackoverflow上进行了搜索,似乎找不到相同的问题。 I assume, therefore, the solution is something simple that is just a gap in my knowledge. 因此,我认为解决方案很简单,仅是我所知。 Please enlighten me. 请赐教。 How do I either get this to bubble up to my general error handler or return a response to the browser from here? 我该如何使它冒泡到我的常规错误处理程序,或者从此处向浏览器返回响应?

You should not redefine req , res , and next in the catch. 您不应该在catch中重新定义reqresnext They will be accessible from the parent scope but by including them in the catch they will be undefined as a then/catch will only have a single argument. 它们可以从父作用域访问,但是通过将它们包含在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()
    });
});

If you want to write the same code with async/await which lets you write asynchronous code in a synchronous syntax. 如果要使用async/await编写相同的代码,则可以使用同步语法编写异步代码。 When you add async the function will automatically return a Promise. 添加async该功能将自动返回Promise。 Using await will wait for a Promise to resolve (or throw an error) without going into indendentation hell (in this case the result of the user creation). 使用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