Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to send response in async await try catch block

I have seen 2 different examples and would like to know which is 'right' or if it doesn't make much difference. Example 1 is sending the response inside the try and example 2 is sending outside of the try block.

Example 1:

  try {
    await food.save();
    res.status(201).send(food);
  } catch (err) {
    res.status(500).send(err);
  }

Example 2:

  try {
    await food.save();
  } catch (err) {
    res.status(500).send(err);
  }

  res.status(201).send(food);
like image 490
user8463989 Avatar asked Nov 17 '25 23:11

user8463989


1 Answers

In first example, if await food.save(); throws an error, then code below it won't execute and the execution will move to the catch block. Client will receive a response with status code of 500.

In second example, if await food.save(); fails, catch block will execute, server will send a response to the client with the status code of 500 and then the last statement will also execute which is probably not what you want. You will also get an error that you cannot re-send the headers once they have been sent. This is because your code will try to send the response to the client twice.

You should use first example because you only want to send the success response if the document is saved in the database successfully.

like image 84
Yousaf Avatar answered Nov 20 '25 14:11

Yousaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!