Home > Blockchain >  try/catch block not working on express js
try/catch block not working on express js

Time:06-07

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!'})
  }
})

CodePudding user response:

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

  • Related