New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Error thrown by middleware should be caught and passed to next() #3483
Comments
This is a possible fix I implemented via a patch (using https://github.com/othiym23/shimmer)
|
@sgilroy sorry for taking a while to get back to you. In general, mongoose tries to defer exception handling to userland where possible, so it'll kill the process if there's an exception in stuff like callbacks or middleware. This definitely seems a little weird in the ES6 paradigm, but IMO it's the right behavior for ES5 code. |
Hey @vkarpov15, I have just faced this same issue and it took me a while until I realized the error was in a mongoose middleware. TBH I didn't know mongoose would silently kill the process upon any uncaught exception in middlewares. Maybe we could get something printed out in When I realized where the error was, my next thought was why mongoose wouldn't just fail the operation (reject promise in my case but the same would apply to callbacks). Do you still think this wouldn't be the right thing to do? Just curious, what side effect could it cause? Cheers! |
It fails silently? Can you provide a code sample that demonstrates this? As far as I know, mongoose just throws an exception, which means node logs it to the console and exits the process. |
… next() and done() once Re: Automattic/mongoose#3483
Fixed in 5.0 branch 👍 |
Hey, thank you very much! |
@vkarpov15 Is there a recommended way to handle this in 4.x? Can I set an exception handler early in the middleware chain, or..? Thanks. |
@SnidelyWhiplash The only way is to just wrap your entire middleware in a function wrapMongooseMiddleware(fn) {
return function(next) {
try {
fn(next);
} catch (error) {
next(error);
}
}
}
// Later
Model.pre('save', wrapMongooseMiddleware(function(next) {
throw new Error('Oops!');
})); What is preventing you from upgrading to Mongoose 5.x? |
Any uncaught exception in a mongoose pre-save middleware gets ignored and results in the save operation never completing (callback never called or promise never resolved/rejected). For our application, it seems like it would be desirable if mongoose would catch all of these errors and pass them to next() automatically, instead of requiring us to add error handling to every single middleware function. Is there some reason for not implementing such a solution in mongoose?
The example below shows a failing test due to the middleware throwing an error:
Output (tested with mongoose@4.1.12):
The text was updated successfully, but these errors were encountered: