I am an absolute NodeJS beginner and want to create a simple REST-Webservice with Express and Mongoose.
Whats the best practice to handle errors of Mongoose in one central place?
When anywhere an database error occurs I want to return a Http-500-Error-Page with an error message:
if(error) {
res.writeHead(500, {'Content-Type': 'application/json'});
res.write('{error: "' + error + '"}');
res.end();
}
In the old tutorial http://blog-next-stage.learnboost.com/mongoose/ I read about an global error listener:
Mongoose.addListener('error',function(errObj,scope_of_error));
But this doesn't seem to work and I cannot find something in the official Mongoose documentation about this listener. Have I check for errors after every Mongo request?
If you're using Express, errors are typically handled either directly in your route or within an api built on top of mongoose, forwarding the error along to
next
.The
NotFoundError
could be sniffed in your error handler middleware to provide customized messaging.Some abstraction is possible but you'll still require access to the
next
method in order to pass the error down the route chain.As for centrally handling mongoose errors, theres not really one place to handle em all. Errors can be handled at several different levels:
connection
errors are emitted on theconnection
your models are using, soFor typical queries/updates/removes the error is passed to your callback.
If you don't pass a callback the error is emitted on the Model if you are listening for it:
If you do not pass a callback and are not listening to errors at the
model
level they will be emitted on the modelsconnection
.The key take-away here is that you want access to
next
somehow to pass the error along.