使用node.js进行Javascriptasynchronousexception处理
我目前正在研究一个node.js应用程序,我有通常的asynchronous代码问题。
我正在Node的HTTP模块上实现一个服务服务器。
这个服务器支持(表示)路线。 例如,我有这样的代码:
server.any("/someRoute",function(req,resp){ resp.end("this text is sent to clients via http") });
服务器需要能够承受失败,当传递给任何一个函数有问题时,我不想让整个服务器崩溃。 当我写代码看起来像这样的问题发生:
server.any("/someRoute",function(req,resp){ setTimeout(function(){ throw new Error("This won't get caught"); },100); });
我不明白我怎么可能在这里发现错误。 我不想通过一个服务器端故障使服务器崩溃,而是想要服务500。
我能想出的唯一解决scheme实际上并不具有performance力。 我只想出了使用process.on("uncaughtException",callback)
和类似的代码使用节点0.8 Domains
(这是一个部分的补救措施,但领域是目前越野车,这仍然不是很有performance力,因为我最终不得不创造每个句柄的一个域)。
我想完成的是throw
一个函数的throw
动作绑定到一个作用域,理想的解决scheme就像将所有抛出的错误从一个函数绑定到一个特定的处理函数一样。
这可能吗? 在这种情况下处理错误的最佳做法是什么?
我想强调的是,它应该能够继续服务请求后,不良请求,并重新启动服务器的每个请求或创build域的每个处理程序和捕获他们的未捕获的exception对我来说似乎是一个坏主意。 另外 – 我听到承诺可能会帮助我(有关兑现承诺的事情),可以承诺在这种情况下援助我吗?
警告 :我不会推荐使用域名的原始答案,域名将来会被弃用,我写了原始答案很有趣,但我不再相信它太相关。 相反,我build议使用事件发射器和有更好的error handling的承诺 – 下面是承诺的例子。 这里使用的承诺是蓝鸟 :
Promise.try(function(){ throw new Error("Something"); }).catch(function(err){ console.log(err.message); // logs "Something" });
随着超时(注意,我们必须返回Promise.delay):
Promise.try(function() { return Promise.delay(1000).then(function(){ throw new Error("something"); }); }).catch(function(err){ console.log("caught "+err.message); });
通用的NodeJSfunction:
var fs = Promise.promisifyAll("fs"); // creates readFileAsync that returns promise fs.readFileAsync("myfile.txt").then(function(content){ console.log(content.toString()); // logs the file's contents // can throw here and it'll catch it }).catch(function(err){ console.log(err); // log any error from the `then` or the readFile operation });
这种方法既快速又安全,我推荐使用下面的答案,它使用的域可能不在这里。
我结束了使用域,我创build了以下文件,我叫mistake.js
其中包含以下代码:
var domain=require("domain"); module.exports = function(func){ var dom = domain.create(); return { "catch" :function(errHandle){ var args = arguments; dom.on("error",function(err){ return errHandle(err); }).run(function(){ func.call(null, args); }); return this; }; };
以下是一些示例用法:
var atry = require("./mistake.js"); atry(function() { setTimeout(function(){ throw "something"; },1000); }).catch(function(err){ console.log("caught "+err); });
它也像正常捕获同步代码一样工作
atry(function() { throw "something"; }).catch(function(err){ console.log("caught "+err); });
我将不胜感激关于解决scheme的一些反馈
在一个侧面说明,在v 0.8显然,当你在领域的exception,它仍然泡沫process.on("uncaughtException")
。 我在process.on("uncaughtException")
处理了这个
if (typeof e !== "object" || !e["domain_thrown"]) {
但是,文档build议反对process.on("uncaughtException")
任何方式