node.js - 基本的node.js问题: handling an exception

标签 node.js

考虑以下代码:

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/

相关文章:

node.js - MongoDb + Mongoose QueryStream - 以下文档更改

javascript - 在其他类中使用类属性

node.js - 找到 Sequelize 。如何在查找查询中包含常量值属性

node.js - pg-promise 事务响应

javascript - Node.js 身份验证 : Using passport with Express

node.js - Nodejs 和 Socket.io 中的实时协作文本编辑器

node.js - GPS设备和 Node 实现

javascript - node.js 中的变量 "security"

javascript - Zombie.js 单击 Javascript 链接

javascript - Javascript中有重复声明优化吗?