0

I'm using Node JS application that connects to Kakfa using kafka-node. I'm catching some exceptions is there is any errors in connecting to kafka. Here is the code. I'm getting can't set headers after they are sent. What is the best way to avoid this?

// Some processing goes above
producer.on('error', function(err){
    console.log(err);
    res.status(500).send("Oh uh, something went wrong");
})
res.end();

I'm pretty sure it is because code is continuing after the error loop. How can I avoid this situation without removing send in error handler.

Flip
  • 6,233
  • 7
  • 46
  • 75
gwthm.in
  • 638
  • 9
  • 24
  • Based on shared code I am not getting error. But usually error occurs when you try to set response after sending response. – Dnyanesh Jan 16 '17 at 11:56
  • When the code enters the error handler function, i'm doing send. I guess this is where the connection ends, and sets headers. When it is out of loop, again, i'm doing res.end. May be this where the problem is. Correct me if I'm wrong! – gwthm.in Jan 16 '17 at 12:34

1 Answers1

0

actually your problem is that your'e using res.send from express, and res.send automatically does res.end(); that is why your'e getting that error, remove res.end()

Yuri Khomyakov
  • 370
  • 2
  • 9
  • Yea, that's true only. But what if the error handler never called? In that case, it is going to call res.end! So, is there any way to avoid calling res.end if res.send already called? – gwthm.in Jan 16 '17 at 14:31
  • I do not see the problem here, if you have an error set the status and send it. It would be helpful to see more of your code as it is unclear what happens if there is no error. Set header error means you are trying to send a response that has been already sent. – Yuri Khomyakov Jan 16 '17 at 15:24