0
var http = require('http'); http.createServer(httpHandler).listen(80);

function httpHandler(req, res)
{
    let some_error = 'shit happened'
    if (some_error) http_send_error(req, res)
    console.log('we should not be here if http error sent')
    costly_processing() 
}

function http_send_error(req, res)
{
  res.writeheader(500, 'Content-type: text/plain')
  res.end("something wrong") 
  die() // I have to break this thread and stop handling this request 
}

How can I break http request handling after this error message was sent by http?

I can write

if (some_error) { http_send_error(req, res); return }

or

if (some_error) http_send_error(req, res)
else {
     //process without error
}

but it looks more verbose and unreadable. How can I break httpHandler after error?

2
  • Hi xoid, will it not exit the handler if you return, following the condition in httpHandler? if (some_error) return http_send_error(req, res) Commented Oct 29, 2019 at 14:32
  • Nice!! Make it the answer, please Commented Oct 29, 2019 at 15:17

2 Answers 2

1

you can return the function and it will execute http_send_error before stopping execution in the the handler.

if (some_error) return http_send_error(req, res)

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

Comments

0

as Ikroneman answered:

you can send the error and stop the handler to further process the request just by returning you error function

if (some_error) http_send_error(req, res)

and in the error handling function no need to "die()"

function http_send_error(req, res)
{
  res.writeheader(500, 'Content-type: text/plain')
  res.end("something wrong") 
  // since you return this function in the handler the request handling will stop here
}

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.