Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling with Mongoose

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?

like image 563
Sonson123 Avatar asked Aug 08 '12 12:08

Sonson123


People also ask

What is Mongoose error?

MongooseError : general Mongoose error. CastError : Mongoose could not convert a value to the type defined in the schema path. May be in a ValidationError class' errors property.

Does Mongoose throw error?

When we run code to save or update the data, all validator runs and if any issue is found by the validator, mongoose throws the error. But these errors are completely different, different validators send errors in different ways.

What problem does Mongoose solve?

The problem that Mongoose aims to solve is allowing developers to enforce a specific schema at the application layer. In addition to enforcing a schema, Mongoose also offers a variety of hooks, model validation, and other features aimed at making it easier to work with MongoDB.

What is .pre in Mongoose?

Sponsor #native_company# — #native_desc# Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins.


Video Answer


1 Answers

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.

app.get('/tickets', function (req, res, next) {   PlaneTickets.find({}, function (err, tickets) {     if (err) return next(err);     // or if no tickets are found maybe     if (0 === tickets.length) return next(new NotFoundError));     ...   }) }) 

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.

PlaneTickets.search(term, next, function (tickets) {   // i don't like this b/c it hides whats going on and changes the (err, result) callback convention of node }) 

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 the connection your models are using, so

mongoose.connect(..); mongoose.connection.on('error', handler);  // or if using separate connections var conn = mongoose.createConnection(..); conn.on('error', handler); 

For typical queries/updates/removes the error is passed to your callback.

PlaneTickets.find({..}, function (err, tickets) {   if (err) ... 

If you don't pass a callback the error is emitted on the Model if you are listening for it:

PlaneTickets.on('error', handler); // note the loss of access to the `next` method from the request! ticket.save(); // no callback passed 

If you do not pass a callback and are not listening to errors at the model level they will be emitted on the models connection.

The key take-away here is that you want access to next somehow to pass the error along.

like image 80
aaronheckmann Avatar answered Nov 10 '22 10:11

aaronheckmann