0

I am trying to catch errors instead of throwing them. I attempted try/catch but realised that didn't work so im at a bit of a loose end. The two errors are mongodb related, however i think node/express errors are still thrown.

app.get( "/test/:lastName", function ( reqt, resp ) {
  var driverName = reqt.params.lastName
  mongoClient.connect( "mongodb://localhost/enteprise",
  function( err, db ) {
  if ( err ) {
    console.error("1 mess " + err)
  }
  var database = db.db( "enteprise" )
  var collection = database.collection( "driversCol" )

  collection.findOne( { lastName : driverName },

  function( err, res ) {
    if ( err ) {
        console.error("2 mess " + err)
    }
    resp.json( res.rate )
    db.close()
    })
  })
})

CASES

if I curl -X GET localhost:3000/test/Owen then '43' should be returned as thats the rate.

currently if i curl -X GET localhost:3000/test/Cressey it throws a type error as its not in the database.

How do I catch errors given the above code and example?

5
  • Are you asking how to convert the code above to use promises like then and catch instead of the current system above of callbacks? Commented Mar 16, 2018 at 17:34
  • Whatever can handle errors instead of doing what it is doing now of throwing them Commented Mar 16, 2018 at 17:41
  • What version of mongodb are you using? Commented Mar 16, 2018 at 17:48
  • And also what version of node.js? Commented Mar 16, 2018 at 17:48
  • node v8.9.4, mongo v3.6.3 Commented Mar 16, 2018 at 17:51

2 Answers 2

2

First, I think you should use next() to send back the errors you are getting in your callbacks:

app.get( "/test/:lastName", function ( req, resp, next ) {
  // some code...
    if ( err ) {
      return next("1 mess " + err)
    }

About the TypeError, it's happening because you are getting undefined from MongoDB when there's not any result, but that's not an error so it will not enter the if. You should check the existence of objects in these cases, for example:

resp.json( res && res.rate || {} )

Here you have another example about how to handle error in these cases:

app.param('user', function(req, res, next, id) {

  // try to get the user details from the User model and attach it to the request object
  User.find(id, function(err, user) {
    if (err) {
      next(err);
    } else if (user) {
      req.user = user;
      next();
    } else {
      next(new Error('failed to load user'));
    }
  });
});
Sign up to request clarification or add additional context in comments.

5 Comments

Can you give any examples where mongo would throw an error?
Some of them: Not passing correct parameters/using a bad syntax. Internal errors such as a connection error. Trying to insert a document with a unique id (like the _id field) that already exists :)
res && res.rate || {} I can't work out the logic of this, but it works. Could you explain please? Also which library provides User?
First res && res.rate is checking if res exists, in case it does it will try to get res.rate (here we are evading the TypeError). Then || {} is just returning an empty object as a default value just in case res or res.rate was a falsy value (e.g. undefined).
1

MongoDB will return an empty object if the requested query cannot be found. So you need to consider how to handle those responses, as Antonio Val posits in his answer.

However, errors can be handled differently than using next(), such as passing the resp to a function for handling errors that calls resp.json() with an error object or other custom message and adding a statusCode so that the callee of the endpoint can also handle errors.

For instance, change wherever you call this:

if ( err ) {
    console.error("1 mess " + err)
}

To this:

if ( err ) {
    console.error("1 mess " + err)
    handleErrors(resp, err)
}

Then create the function handleErrors():

function handleErrors(resp, err) {
    // its up to you how you might parse the types of errors and give them codes,
    // you can do that inside the function 
    // or even pass a code to the function based on where it is called.

    resp.statusCode = 503;
    const error = new Error(err);
    resp.send({error})
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.