Home > other >  Can I use res.send() on a trycatch block?
Can I use res.send() on a trycatch block?

Time:10-11

I am using a node route and I use a trycatch block but Node.js is not having it. When there is an error with the code and it goes to the catch, it fails.

try {
 ... 
 res.send({ message: 'All good nothing wrong with the code above' })
} catch {
 res.status(500).send({ message: 'There is an error I want to send to the front end' })
}

Node clearly is not happy about this, I know I cannot send res.send()twice but it is on a trycatch block. How do I send an error message back the front end if something fails?

Node complains with on the catch block:

'Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client'

UPDATE

I fixed it by sending the error object with throw to the catch block and not to use res.send() on the try catch for any conditional other than just once

CodePudding user response:

It is always good to terminate the execution flow of the function when you want to send something and not do anything else afterwards.

res.send('All ok');
console.log('Response sent');
return;

or

return res.send('All ok');


try {
   throw Error('Oops')
   return res.send('OK')
} catch(error) {
   return res.send('Not OK: '   error.message)
}

CodePudding user response:

You can't use two times res.send so add return.

try {
 ... 
} catch {
   res.status(500).send({ message: 'There is an error I want to send to the front end' })
   return;
}
res.send({ message: 'All good nothing wrong with the code above' })
  • Related