JoeBoggs
JoeBoggs

Reputation: 301

How to handle errors in Node.js/express

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?

Upvotes: 0

Views: 60

Answers (2)

wlh
wlh

Reputation: 3525

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})
}

Upvotes: 1

Antonio Val
Antonio Val

Reputation: 3340

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'));
    }
  });
});

Upvotes: 2

Related Questions