4

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.

Ashh
  • 44,693
  • 14
  • 105
  • 132
Temp O'rary
  • 5,366
  • 13
  • 49
  • 109

2 Answers2

3

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

Ashh
  • 44,693
  • 14
  • 105
  • 132
  • user.find is not triggering the catch probably, since is not considered an exception that the user is not found. That would only work for a more "unexpected error" in this case... – Javier Aviles Jun 18 '18 at 09:44
  • @JavierAviles For your kind information "user not found" is not a callback error... It is just a condition when no crieria is matched in the database and please don't update the answer after seeing others answer – Ashh Jun 18 '18 at 09:48
  • I missunderstood that he wanted to control a pure error, I thought he referred to a "user not found" error. My bad there. I updated the unexpected error after doing some searching to improve my answer... Just chill out, I am here just to try to help others like you, in an altruistic way... whats wrong with people nowadays... – Javier Aviles Jun 18 '18 at 09:59
  • @JavierAviles I appreciate your efforts... BTW I didn't down vote you. You can delete your answer to regain your reputations... Thanks – Ashh Jun 18 '18 at 10:01
  • Guys if you read my question, I'm also asking for a centralised function where all such error handlings can be handled. How can I achieve that? – Temp O'rary Jun 18 '18 at 10:14
  • @TempO'rary There is no centralised function here... you need to create a custom function for this in which you will simply throw your error... – Ashh Jun 18 '18 at 10:19
  • Maybe if you create a middleware with the try/catch an capture there mongoose exceptions? – Javier Aviles Jun 18 '18 at 10:21
  • How can we do that? – Temp O'rary Jun 18 '18 at 10:22
  • 1
    Something like this would be to do it as a middleware: https://github.com/koajs/koa/blob/master/docs/error-handling.md but would capture every exception, would be a global solution. If you only want mongoose exceptions, you could do it as the updated Ashish answer – Javier Aviles Jun 18 '18 at 10:27
  • @Ashish, your "And here is your query 2" is not what i meant for my second query. However, your shared link helped. Thanks – Temp O'rary Jun 18 '18 at 10:39
  • @TempO'rary For each and every query you can use single function to return the error that's what I meant... And btw the link is shared by `Javier Aviles` – Ashh Jun 18 '18 at 10:41
  • @JavierAviles and Ashish, Thanks to you both appreciate your help. – Temp O'rary Jun 18 '18 at 10:54
  • The link to https://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/ was especially helpful. – Temp O'rary Jun 18 '18 at 10:55
  • Can you guys just one more tiny question please? Does Mongoose have its own error handling mechanisms? – Temp O'rary Jun 18 '18 at 11:10
  • @TempO'rary No mongoose is just a **object modelling tool** and used to establish connection between your sever and database... – Ashh Jun 18 '18 at 11:14
  • Don't want to be a pain with middleware, from Mongoose 4.5.0 you have the ability to handle errors in middleware. I don't know if this could be of your interest, but If you scroll down [here](http://mongoosejs.com/docs/middleware.html) until the "Error handling" section, you may found something useful. In Mongoose you can set pre or post middlewares. You define an error handler the same way you define a normal post middleware. An error handler middleware only gets called when an error occurred. This [link](http://thecodebarbarian.com/mongoose-error-handling) could also be useful for you. – Javier Aviles Jun 18 '18 at 13:47
3

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

vkarpov15
  • 3,614
  • 24
  • 21