Kevin Martin
Kevin Martin

Reputation: 53

Nodejs response and console

I am creating a NodeJS API using Express, PostgreSQL in which I created a controller function which will check the user from the database.

const checkUser = async (req, res) => {
  try {
    const user = await pool.query('select * from users where email = $1', [req.body.email]);

    if (user.rows.length === 0) throw new Error('Error Found');

    return res.json("User Found");
  } catch (e) {

//=======   Output at console ========
//Error: Error Found 

    console.log(e); 

//========  Response Object Received From API ==========
// {
//   "msg": "Error Found",
//   "Error": {}
// }

    res.status(400).send({ msg: 'Error Found', Error: e });

  }
};

Consider the situation that the user is not found in the Database so from try block the control passes to the catch block.

1- I am not able to get why the Error thrown from the try block to catch block sends back an empty object as a response. Also, at the same time using console.log prints the correct output value in the console.
2- I want a fix so that I can send e as a response to the User.

Upvotes: 0

Views: 420

Answers (1)

raina77ow
raina77ow

Reputation: 106453

The problem is that Error objects are not that easy to serialize (which is intentional). This...

try { 
  throw new Error('Catch me if you can');
} catch(e) { 
  console.log(JSON.stringify(e)); // {}
}

... just logs {}, the same as for empty object, because Error objects don't have enumerable properties. And in your case, you don't send that object directly - but make it a property of another object sent to client.

However, there are several ways out of this. If you always need your client to get all the details of an Error, cast that to string (as toString() is overridden):

try { 
  throw new Error('Catch me if you can');
} catch(e) { 
  console.log(JSON.stringify(e.toString())); // "Error: Catch me if you can"
}

... or use Error object properties - name and message - as separate fields of your response:

res.status(400).send({ 
  name: e.name || 'Anonymous Error',
  msg: e.message || 'no message provided' 
});

As sub-approach, you might consider choosing your status code based on type of error you have (always sending 404 for 'not founds', for example).

Upvotes: 0

Related Questions