0

I wrote a resource, to which a user can send data. If the data does not validate (validation returns false), I need to send an error 500 status code to the client, but the problem is, that when I use res.status(500), the program exits and I just want to cancel this request with an error to the client, not stopping the program...

function formHandler(req, res, next) {
    let isValid = validate(fields.token)
    if (!isValid) {
        res.status(500).send({ error: 'invalid!' })
    }
5
  • 1
    You might want a return after that line, or your code will continue and do stuff it's not meant to in error state. Commented Aug 15, 2018 at 10:35
  • Please add more code. I think res is not defined in that scope Commented Aug 15, 2018 at 10:38
  • @Keith - what do you mean , can you provide example ? Commented Aug 15, 2018 at 11:06
  • @FarhanYaseen done please see Commented Aug 15, 2018 at 11:08
  • @shopiaT Posted an example, ps. In a way I'm assuming this is the problem, the thing is you don't provide what code comes next, or even if your using an else block. Or more importantly any error message node might be giving.. Commented Aug 15, 2018 at 11:57

1 Answer 1

1

Please note, doing res.status(500).send({ error: 'invalid!' }) will not terminate the current function..

So ->

function formHandler(req, res, next) {
  let isValid = validate(fields.token)
  if (!isValid) {
    res.status(500).send({ error: 'invalid!' })
  }
  //so the code below will even run in invalid state
  res.send("this piece of code will run no matter what");

You could either call return, or use an else block.. eg.

function formHandler(req, res, next) {
  let isValid = validate(fields.token)
  if (!isValid) {
    res.status(500).send({ error: 'invalid!' });
    return;
  }
  res.send("this piece of code will only run if isValid");

Doing a second res.send again is most likely giving you the error, as the first res.send would have closed the connection..

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.