Muhammad Hannan Muhammad Hannan - 12 days ago 6
Node.js Question

Handling 503 Error in Express/Node.js especially in TryCatch case

I have a special case for which I want to clear the possible reason for 503 Error. The following code snippet has a catch statement which runs when system is not able to find any results

app.post('/api/fetch/user', function(req, res){
var email = req.body.emailTxt;
db.one('SELECT * FROM users WHERE email=$1', [email])
.then(function(data){
console.log('DATA:', data);

var userCard = { id: data.user_id, name: data.user_name,
email: data.email, regDate: data.date_created };

res.status(200).json({ 'valid': true, '_payload': userCard });
})
.catch(function(error){
if(error.search(/No data returned from the query/im) > 0) // regex case insensitive search and search multiline as source string is multiline
res.status(500).send('Invalid Request Match');
else
res.status(500).send('ERROR: '+error);
})


});


When my API call is made to this API end point and when no result found the control moves in
catch()
which is fine but quite strangely it returns
503 - Request timeout
error.
I have tried to to remove conditions in
if()
in order to debug but seems like no matter what but the
if-else
does not seem working in ExpressJs.


Note: Everything works well and also when control stays in
.then()
. If I remove
if,else
and keep simple error display/response return then everything works ok. There is nothing special included in my API; it is only one single page script I prepared to test API.

Answer

I think you got error in the .catch block.

Try to modify the code and see if this helps:

app.post('/api/fetch/user', function(req, res){
     var email = req.body.emailTxt;
     db.one('SELECT * FROM users WHERE email=$1', [email])
         .then(function(data){
             console.log('DATA:', data);

             var userCard = { id: data.user_id, name: data.user_name, 
                              email: data.email, regDate: data.date_created };

             res.status(200).json({ 'valid': true, '_payload': userCard });
         })
         .catch(function(error){
           console.error(error); //never ignore errors!
           try {
             //i think error is an Error Object here, so it doesn't have .search function
             if(error.search(/No data returned from the query/im) > 0)    // regex case insensitive search and search multiline as source string is multiline
                res.status(500).send('Invalid Request Match');
             else 
                res.status(500).send('ERROR: '+error);
           } catch (err) {
             console.error(err);
              res.status(500).send('some unknown error');
           };
         });
      });
  1. Edit: Sorry, removed .finally because you may send response twice.

  2. Edit, better approach to handle error in .catch block.


//make catch block error safe to make sure no error occurs
if (error && error.message == 'No data returned from the query.') {
  res.status(500).send('Invalid Request Match');
} else {
  res.status(500).send('ERROR: '+error);
}