Error handling in async await

ぃ、小莉子 提交于 2019-12-10 17:44:21

问题


How can you implement error handling for Mongoose (current version v5.1.5)?

For example, let's assume the following code where a user detail is being looked up.

let u = await user.find({ code: id }).lean();
return u;

And some error occurs, how should it be handled?

Secondly, can we have centralised error handling function which will get triggered whenever an error happens in any of the Mongoose code, it gets directed to a particular function in the project where it can be handled.


回答1:


You will get error in .catch method of async await

Suppose you have a function

handleErrors(req, res, err) {
  return res.json({
    success: false,
    message: err,
    data: null
  })
}

And here is your query

try {
  let u = await user.find({ code: id }).lean();
  return u;
} catch(err) {
  handleErrors(req, res, err)  //You will get error here
}

You can check here for more




回答2:


Mongoose maintainer here. The first question has been answered correctly. Re: "Secondly, can we have centralised error handling function which will get triggered whenever an error happens in any of the Mongoose code, it gets directed to a particular function in the project where it can be handled.", try this:

async function run() {
 await mongoose.connect(connectionString);

  const schema = new mongoose.Schema({ n: Number });

  schema.post('findOne', function(err, doc, next) { console.log('Got error', err.stack); });

  const Test = mongoose.model('Test', schema);

  console.log(await Test.findOne({ n: 'not a number' }));
}

Here's my blog post on Mongoose error handling middleware



来源:https://stackoverflow.com/questions/50905750/error-handling-in-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!