考虑以下代码:
var meryl = require('meryl'),
merylex = require('meryl-extras'),
staticfile = merylex('staticfile'),
httpserv = require('http');
meryl.p('GET /static/<filepath>', staticfile({root: 'static', path: 'filepath'}));
httpserv.createServer(meryl.cgi()).listen(3000);
这非常有效,直到您请求一个不存在的文件为止。如果我请求 /static/non-existent-file
,服务器崩溃并显示:
/home/user/.node_libraries/meryl-extras/lib/plugins/staticfile.js:224 chain(); ^ TypeError: undefined is not a function at CALL_NON_FUNCTION (native) at /home/user/.node_libraries/meryl-extras/lib/plugins/staticfile.js:224:9 at [object Object]. (fs:58:5) at [object Object].emit (events:27:15) at fs:655:12 at node.js:608:9
我怎样才能捕捉到这个,这样我的应用程序就不会崩溃?不幸的是,作为一种新语言,我似乎找不到很多示例。
谢谢。
最佳答案
在node.js中,您可以通过监听全局process
对象中的uncaughtException
事件来捕获try block 之外的异常。像这样:
process.on('uncaughtException', function (exception) {
console.error(exception);
});
这可以捕获 try
block 中未包含的代码中引发的异常,并且还可以防止脚本立即终止(对于运行服务器来说非常有用,即使出现意外问题,服务器通常也应该保持运行)。
关于node.js - 基本的node.js问题: handling an exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3782571/