【发布时间】:2012-05-10 13:32:44
【问题描述】:
我浏览了 Express 的文档,the part describing error handling 对我来说完全不透明。
我认为他们所指的app 是一个实例createServer(),对吗?但是我不知道在处理请求期间发生异常时如何阻止 node.js 炸毁应用程序进程。
我真的不需要任何花哨的东西;每当出现异常时,我只想返回 500 的状态,再加上一个空响应。节点进程不得仅仅因为某处存在未捕获的异常而终止。
有没有一个简单的例子说明如何做到这一点?
var express = require('express');
var http = require('http');
var app = express.createServer();
app.get('/', function(req, res){
console.log("debug", "calling")
var options = {
host: 'www.google.com',
port: 80,
path: "/"
};
http.get(options, function(response) {
response.on("data", function(chunk) {
console.log("data: " + chunk);
chunk.call(); // no such method; throws here
});
}).on('error', function(e) {
console.log("error connecting" + e.message);
});
});
app.configure(function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.listen(3000);
使整个应用程序崩溃,产生回溯
mypath/tst.js:16
chunk.call(); // no such method; throws here
^ TypeError: Object ... has no method 'call'
at IncomingMessage.<anonymous> (/Library/WebServer/Documents/discovery/tst.js:16:18)
at IncomingMessage.emit (events.js:67:17)
at HTTPParser.onBody (http.js:115:23)
at Socket.ondata (http.js:1150:24)
at TCP.onread (net.js:374:27)
【问题讨论】:
-
just because there was an uncaught exception somewhere.如果出现未捕获异常,进程将终止。如果你不希望它在异常发生时终止,捕获异常并返回 500 错误。 -
您可能对非快递方式感兴趣:stackoverflow.com/questions/4213351/…
-
太好了,非常感谢@Matt!