以下是我的代码:
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);
为什么server1.on(“error”,...)不处理回调引发的异常并且进程停止了? 如果通过监听“错误”事件无法处理此类异常, 我怎么能处理这样的异常,以便http服务器从那时起仍能正常运行?
答案 0 :(得分:3)
使用emit
代替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);