异步node.js调用中的错误处理 [英] error handling in asynchronous node.js calls
问题描述
我对node.js很新,虽然我一般很熟悉JavaScript。我的问题是关于如何处理node.js中的错误的最佳实践。
I'm new to node.js although I'm pretty familiar with JavaScript in general. My question is regarding "best practices" on how to handle errors in node.js.
通常在编写Web服务器,FastCGI服务器或各种语言的网页时在多线程环境中使用阻止处理程序的异常。当请求进来时,我通常会这样做:
Normally when programming web servers, FastCGI servers or web pages in various languages I'm using Exceptions with blocking handlers in a multi-threading environment. When a request comes in I usually do something like this:
function handleRequest(request, response) {
try {
if (request.url=="whatever")
handleWhateverRequest(request, response);
else
throw new Error("404 not found");
} catch (e) {
response.writeHead(500, {'Content-Type': 'text/plain'});
response.end("Server error: "+e.message);
}
}
function handleWhateverRequest(request, response) {
if (something)
throw new Error("something bad happened");
Response.end("OK");
}
这样我可以随时处理内部错误并向用户发送有效的回复
This way I can always handle internal errors and send a valid response to the user.
我明白,对于node.js,一个应该做非阻塞调用,这显然会导致各种数量的回调,如下例所示:
I understand that with node.js one is supposed to do non-blocking calls which obviously leads to various number of callbacks, like in this example:
var sys = require('sys'),
fs = require('fs');
require("http").createServer(handleRequest).listen(8124);
function handleRequest(request, response) {
fs.open("/proc/cpuinfo", "r",
function(error, fd) {
if (error)
throw new Error("fs.open error: "+error.message);
console.log("File open.");
var buffer = new require('buffer').Buffer(10);
fs.read(fd, buffer, 0, 10, null,
function(error, bytesRead, buffer) {
buffer.dontTryThisAtHome(); // causes exception
response.end(buffer);
}); //fs.read
}); //fs.open
}
此示例将完全杀死服务器因为异常没有被捕获。
我的问题在这里,我不能再使用一个try / catch了,因此通常不会捕获在处理请求期间可能引起的任何错误。
This example will kill the server completely because exceptions aren't being catched. My problem is here that I can't use a single try/catch anymore and thus can't generally catch any error that may be raised during the handling of the request.
当然,我可以在每个回调中添加一个try / catch,但是我不喜欢这种方法,因为这样做是由程序员决定的,忘记一个try / catch。对于具有大量不同和复杂处理程序的复杂服务器,这是不能接受的。
Of course I could add a try/catch in each callback but I don't like that approach because then it's up to the programmer that he doesn't forget a try/catch. For a complex server with lots of different and complex handlers this isn't acceptable.
我可以使用全局异常处理程序(防止完整的服务器崩溃),但是我可以不会向用户发送响应,因为我不知道哪个请求导致异常。这也意味着请求保持未处理/打开,浏览器会永久等待响应。
I could use a global exception handler (preventing the complete server crash) but then I can't send a response to the user since I don't know which request lead to the exception. This also means that the request remains unhandled/open and the browser is waiting forever for a response.
有人有一个很好的,坚实的解决方案吗?
Does someone have a good, rock solid solution?
推荐答案
Node 0.8引入了一个名为Domains的新概念。它们非常类似于.net中的AppDomains,并提供了一种封装一组IO操作的方式。它们基本上允许您在上下文特定组中包装请求处理调用。如果该组抛出任何未捕获的异常,那么可以以一种方式处理和处理它们,以便您访问所需的所有范围和上下文特定信息,以便成功从错误中恢复(如果可能)。
Node 0.8 introduces a new concept called "Domains". They are very roughly analogousness to AppDomains in .net and provide a way of encapsulating a group of IO operations. They basically allow you to wrap your request processing calls in a context specific group. If this group throws any uncaught exceptions then they can be handled and dealt with in a manner which gives you access to all the scope and context specific information you require in order to successfully recover from the error (if possible).
这个功能是新的,只是刚刚被介绍,所以谨慎使用,但是从我可以告诉它是专门介绍来处理OP正在试图解决的问题。
This feature is new and has only just been introduced, so use with caution, but from what I can tell it has been specifically introduced to deal with the problem which the OP is trying to tackle.
文档可以在以下网址找到: http:// nodejs.org/api/domain.html
Documentation can be found at: http://nodejs.org/api/domain.html
这篇关于异步node.js调用中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!