异步 node.js 调用中的错误处理 [英] error handling in asynchronous node.js calls

查看:20
本文介绍了异步 node.js 调用中的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我对 JavaScript 非常熟悉,但我是 node.js 的新手.我的问题是关于如何处理 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 引入了一个名为域"的新概念.它们与 .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

这篇关于异步 node.js 调用中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆