mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

how can i handle the create err?

Open aweiu opened this issue 10 years ago • 4 comments

i try to do that:

model.on('error',fun)
model.create(obj)

but the handler doesn't work.

aweiu avatar Jul 11 '16 06:07 aweiu

This is how you handle errors:

Model.create(obj, function(err, insertedObj) {
    if (err) {
      // handle error
    } else {
      // the object was inserted
    }
  });

enrichz avatar Jul 11 '16 14:07 enrichz

@enrichz thank you,but,it's not i need. i don't want all the create/find/delet/etc action need to do that,i want handler all the errors on top

aweiu avatar Jul 14 '16 03:07 aweiu

I don't think you can do what you want, and also I would not advice to do that. I think it's a good idea to handle the errors separately. What you can do anyway, it's to create a middleware to handle the errors coming from mongoose, but you still need to write some code for every operation. The code could be like this:

Model.create(obj, function(err, insertedObj) {
    if (err) {
      return next({"erorr_type": "mongoose", "error": err});
    } else {
      // the object was inserted
    }
  });

and the middleware could be something like this:

module.exports.handleMongooseErrors = function (err, req, res, next) {
  if(err.erorr_type == "mongoose") {
    // handle here all mongoose errors
  }
  else {
    // pass the error to the next error handler
    next(err);
  }
};

I hope this helps.

enrichz avatar Jul 14 '16 07:07 enrichz

@aweiu that's not supported in mongoose atm. Is there somewhere in the docs that pointed you in this direction?

vkarpov15 avatar Jul 15 '16 19:07 vkarpov15