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

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

问题描述

我是node.js的新手,虽然我对JavaScript一般都很熟悉。我的问题是关于如何处理node.js中的错误的最佳实践。



通常,当编程Web服务器,FastCGI服务器或各种语言的网页在多线程环境中使用阻塞处理程序的异常。当请求进来时,我通常做这样的事情:

  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);
}
}

函数handleWhateverRequest(request,response){
if(something)
throw new Error(something bad happened);
Response.end(OK);
}

这样我总是可以处理内部错误并向用户发送有效的响应。



我理解,使用node.js时,应该执行非阻塞调用,这显然会导致不同数量的回调,例如:

  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。
$ b var buffer = new require('buffer')。buffer(10);
fs.read(fd,buffer,0,10,null,
function(error,bytesRead,缓冲区){

buffer.dontTryThisAtHome(); //导致异常

response.end(buffer);
}); //fs.read

}); //fs.open

}

因为例外没有被抓住。
我的问题是,我不能使用单个try / catch,因此通常不能捕获在处理请求期间可能引发的任何错误。



当然,我可以在每个回调中添加一个try / catch,但是我不喜欢这种方法,因为那是由程序员来决定的,忘记一个try / catch。对于一个有很多不同的复杂处理程序的复杂服务器,这是不能接受的。



我可以使用一个全局异常处理程序(防止整个服务器崩溃)不向用户发送响应,因为我不知道哪个请求导致异常。这也意味着请求仍然处于未处理/打开状态,浏览器将永远等待响应。



有人有一个好的,坚如磐石的解决方案吗?

$节点0.8引入了一个称为域的新概念。它们非常类似于.net中的AppDomains,并提供了一种封装一组IO操作的方法。它们基本上允许您在上下文特定组中封装请求处理调用。如果这个组抛出任何未捕获的异常,那么它们可以以一种方式处理和处理,它允许您访问所需的所有范围和上下文特定信息,以便从错误中成功恢复(如果可能)。



这个功能是新的,刚才刚刚介绍过,所以谨慎使用,但从我可以告诉它已经专门介绍处理OP正试图解决的问题。



文档位于: http://nodejs.org/api /domain.html


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.

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.

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

}

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.

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 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).

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.

Documentation can be found at: http://nodejs.org/api/domain.html

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

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