how can i handle the create err?
i try to do that:
model.on('error',fun)
model.create(obj)
but the handler doesn't work.
This is how you handle errors:
Model.create(obj, function(err, insertedObj) {
if (err) {
// handle error
} else {
// the object was inserted
}
});
@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
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.
@aweiu that's not supported in mongoose atm. Is there somewhere in the docs that pointed you in this direction?