javascript - node js http server error handling - Stack Overflow

The following is my code:const http = require('http');var server1 = http.createServer(functi

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?

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?

Share Improve this question edited Feb 29, 2016 at 17:15 BrTkCa 4,7934 gold badges28 silver badges45 bronze badges asked Feb 29, 2016 at 16:31 Chao WeiChao Wei 512 silver badges5 bronze badges 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. – Soubhik Mondal Commented Feb 29, 2016 at 16:43
Add a ment  | 

1 Answer 1

Reset to default 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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744159860a4561042.html

相关推荐

  • javascript - node js http server error handling - Stack Overflow

    The following is my code:const http = require('http');var server1 = http.createServer(functi

    9天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信