0

I'm trying to do an error management in express as per the form input from frontend. I saw that either I can send res.status(401) as error code or res.json({}) as sending error message but not both. What should I do below here to send both simultaneously?

app.post('/verifyOTP', (req, res) => {
  const hash = req.body.hash;
  let [ hashValue, expires ] = hash.split('.');
  let now = Date.now();
    if (now > parseInt(expires)) {
        return res.status(400).json({ error: 'Timeout. Please try again' })
    }
})
Jatin Mehrotra
  • 9,286
  • 4
  • 28
  • 67
Rahul Ahire
  • 161
  • 3
  • 15

2 Answers2

2

You can always do this

what enables send to send object :- When the parameter is an Array or Object, Express responds with the JSON representation: for more reference express docs for send

How can i combine .status and .send?:-Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode. for more reference express status docs

app.post('/verifyOTP', (req, res) => {
  const hash = req.body.hash;
  let [ hashValue, expires ] = hash.split('.');
  let now = Date.now();
    if (now > parseInt(expires)) {
        return res.status(400).send({ error: 'Timeout. Please try again' })
    }
})
Jatin Mehrotra
  • 9,286
  • 4
  • 28
  • 67
  • I tried it and doesn't seem to work at all. I can only get either one of them – Rahul Ahire Oct 19 '20 at 14:47
  • 1
    did you tried this in Postman? ofcourse in browser you will only get `error message`. – Jatin Mehrotra Oct 19 '20 at 14:53
  • oh yes it is working in postman. But how can I `console.log` or display the error code and message in frontend with axios I tried `data.data.error` in response cycle and I cant get the error message. Any suggestion what should I do? – Rahul Ahire Oct 19 '20 at 16:05
  • 1
    when you say console.log just have to write console.log('text') and it will be shown to your in the backend of your server. i haven't worked with axios though but this can help https://itnext.io/javascript-error-handling-from-express-js-to-react-810deb5e5e28, however, i would have tried this like keeping a variable for status code and based on condition i would have send it with res.send({error : nam_of_var, msg:'timeout'). – Jatin Mehrotra Oct 19 '20 at 16:12
  • 1
    I tried this and this working without using axios `res.status(500).send({status:500, message: 'internal error', type:'internal'}); ` – Jatin Mehrotra Oct 19 '20 at 16:17
  • for axios https://stackoverflow.com/a/38798652/13126651, https://stackoverflow.com/a/60825383/13126651,https://stackoverflow.com/a/60869154/13126651 – Jatin Mehrotra Oct 19 '20 at 16:20
1

As mentioned in the docs:

res.status(400).send({ error: 'Timeout. Please try again' })
Ahmad MOUSSA
  • 2,729
  • 19
  • 31