5

The following is my code:

const http = require('http');
var server1 = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2) + '\n' + req.url);
    res.end();
    throw new Error("Error!!!");
});
server1.on("error", err=>console.log(err));
server1.listen(5060);

Why the exception thrown from the callback is not handled by the server1.on("error", ...) and the process is stopped? If such an exception can't be handled by listening on the "error" event, how could I handle such exceptions so that the http server can still run well from the time on?

1
  • 3
    The error in server1.on refers to the error event being emitted by the server and not a thrown Error object as is in your case. To handle the thrown error, you'd need try-catch. Commented Feb 29, 2016 at 16:43

1 Answer 1

5

Use emit instead throw:

const http = require('http');
var server1 = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2) + '\n' + req.url);
    res.end();
    // throw new Error("Error!!!");
    this.emit('error', new Error("Error!!!"));
});
server1.on("error", err=>console.log(err));
server1.listen(5060);
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.