从Node.JS中的未捕获异常恢复 [英] Recover from Uncaught Exception in Node.JS
问题描述
以下是一个示例:
code> var express = require('express');
var app = express.createServer();
var reqNum = 0;
app.get('/ favicon.ico',function(req,res){res.send(404);});
app.get('*',function(req,res,next){
console.log(Request#,++ reqNum,:,req.url);
next();
});
app.get('/ error',function(req,res,next){
throw new Error(Problem occurred);
});
app.get('/ hang',function(req,res,next){
console.log(In / Hang route);
setTimeout(function(){
console.log(In / hang callback);
if(reqNum> = 3)
throw new错误(发生问题);
res.send(It工作!);
},2000);
});
process.on('uncaughtException',function(err){
console.log(Uncaught exception!,err);
});
app.listen(8080);
如果您访问/错误,则会发生异常,但会被捕获。用户收到错误消息 - 没有问题。如果我访问/挂起,服务器最终会抛出一个未被捕获的异常并永久挂起。任何后续的/ hang请求都会挂起。
这很糟糕。任何关于如何解决这个问题的建议?
当一个未捕获的异常发生时,你处于不洁的状态。让进程死机并重新启动,没有什么可以做的,以安全地将其恢复到已知的状态。使用 永远
,它将重新启动您的过程即将死亡。
OK, so I have a problem. If an uncaught exception occurs while I am handling an HTTP request, I have no opportunity to call the end() method on the http.ServerResponse object. Therefore, the server hangs forever and never fulfills the request.
Here's an example:
var express = require('express');
var app = express.createServer();
var reqNum = 0;
app.get('/favicon.ico', function(req, res) {res.send(404);});
app.get('*', function(req, res, next) {
console.log("Request #", ++reqNum, ":", req.url);
next();
});
app.get('/error', function(req, res, next) {
throw new Error("Problem occurred");
});
app.get('/hang', function(req, res, next) {
console.log("In /hang route");
setTimeout(function() {
console.log("In /hang callback");
if(reqNum >= 3)
throw new Error("Problem occurred");
res.send("It worked!");
}, 2000);
});
process.on('uncaughtException', function(err) {
console.log("Uncaught exception!", err);
});
app.listen(8080);
If you visit /error, an exception occurs, but it is caught. The user receives an error message - no problem. If I visit /hang, though, the server will eventually throw an uncaught exception and hang forever. Any subsequent requests for /hang will hang.
This sucks. Any advice for how to fix this issue?
When an uncaught exception occurs, you're in an unclean state. Let the process die and restart it, there's nothing else you can do to safely bring it back to a known-good state. Use forever
, it'll restart your process as soon as it dies.
这篇关于从Node.JS中的未捕获异常恢复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!