Skip to content
Advertisement

try/catch block not working on express js

I try to create one route using express.js with a try/catch block, but when the conditions in the try block are not met, the code just loads without returning any value

any solution for this problem?

app.post('/test', async (req, res) => {
  try {
    const {name} = req.body;

    if (name === 'name') res.status(200).json({message: 'success!'}) // stuck at there
  } catch (err) {
    res.status(500).json({message: 'failed!'})
  }
})

Advertisement

Answer

You are not responding anything to the client in case name !== 'name'

Add an else with a response, or throw an exception that can be caught, and it should work as expected

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement