Reputation: 842
Is it possible to catch and ignore errors in a Mongoose post-save hook, resulting in a successful return (resp. a resolved promise) from a document save
call?
Sample code:
schema.post('save', function postSave(err, doc, next) {
if (err.name === 'MongoError' && err.code === 12345) {
// this does not work the way I'd expect it to
return next();
}
return next(err);
});
The above hook still results in the save
call failing with the original error (next(null)
doesn't help either). I can replace the error by passing a custom one to next
, which shows that the mechanism is generally working, but that doesn't really help me.
The Mongoose middleware docs contain a very similar example (see the "Error Handling Middleware" section near the bottom), but don't really explain the intended behavior of the next
callback.
For context, what I'm trying to accomplish in the actual project is a post-save middleware hook that retries the save call when a duplicate key error is encountered.
Upvotes: 0
Views: 619
Reputation: 18515
However, there is a special kind of post middleware called "error handling middleware" that executes specifically when an error occurs. Error handling middleware is useful for reporting errors and making error messages more readable.
I think it is too late in the hooks chain to do this. It would seem that the pre "save"
hook would be a good place to check for duplicate keys
no? There you can error out and then in your code re-try as you see fit.
The error handling middleware
is more of an error formatting mechanism really.
Upvotes: 1