异步的JavaScript与异常处理的Node.js [英] Javascript Asynchronous Exception Handling with node.js

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

问题描述

我目前工作的一个应用程序的Node.js和我在平时的异步code问题。

I'm currently working on a node.js app and I'm having the usual asynchronous code issue.

我实施节点上的HTTP模块之上的服务服务器。

I'm implementing a service server on top of Node's HTTP module.

该服务器支持(如preSS等)的路线。
比如我有code,看起来像这样:

This server supports (express like) routes. For example I have code that looks like this:

server.any("/someRoute",function(req,resp){
    resp.end("this text is sent to clients via http")
});

服务器需要能够承受失败,我不想崩溃整个服务器当在传递到任何的功能的问题。当我在写code,看起来像会出现问题:

The server needs to be able to withstand failure, I do not want to crash the whole server when there is a problem in a function passed to any. The problem occurs when I'm writing code that looks like:

server.any("/someRoute",function(req,resp){
    setTimeout(function(){
        throw new Error("This won't get caught");
    },100);
});

我不明白我怎么可能可以在这里捕获的错误。我不想在一个服务器端故障导致服务器崩溃,而不是我想为500。

I don't see how I possible can catch the error here. I don't want to crash the server over one server-side glitch, instead I want to serve 500.

的唯一的解决办法,我已经能够拿出真不前pressive。我只是想出了使用使用节点0.8 process.on(uncaughtException,回调)和类似code (这是一个局部的补救办法,但域是目前马车,这仍然不是很EX pressive因为我最终不得不创建每个手柄域)。

The only solutions I've been able to come up with are really not expressive. I've only come up with using process.on("uncaughtException",callback) and similar code using node 0.8 Domains (which is a partial remedy but Domains are currently buggy and this is still not very expressive since I end up having to create a domain for every handle).

我想什么来完成是有约束力的罚球从功能到一个范围的行动,理想的解决方案是一样的东西从一个函数绑定的所有引发的错误,以一个特定的处理程序功能。

What I would like to accomplish is binding throw actions from a function to a scope, the ideal solution is something like binding all thrown errors from a function to a specific handler function.

这可能吗?什么是在这种情况下处理错误的最佳做法?

Is this possible? What is the best practice to handle errors in this case?

我想强调的是,它应该能够继续不好的请求后,服务请求,并重新启动服务器上的每个请求或每处理器创建的域和捕捉他们捕获的异常似乎是一个坏主意给我。此外 - 我听说过的承诺也许能帮助我(一些关于中的承诺抛),可以帮助许诺我在这种情况下

I'd like to emphasise that it should be able to continue serving requests after a bad requests, and restarting the server on every request or creating domains for every handler and catching their uncaught exceptions seems like a bad idea to me. Additionally - I've heard promises might be able to assist me (something about throw in promises), can promises aid me in this situation?

推荐答案

警告:使用域,域正在德$ P $在未来pcated我不会推荐的原来的答案,我有很多乐趣写原来的答案,但我不再相信它太重要。相反 - 我建议使用事件发射器和具有更好的错误处理的承诺 - 这里是下面的例子与承诺来代替。这里使用的承诺是蓝鸟

Warning: I would not recommend the original answer using domains, domains are being deprecated in the future, I had a lot of fun writing the original answer but I no longer believe it is too relevant. Instead - I suggest using event emitters and promises that have better error handling - here is the below example with promises instead. The promises used here are Bluebird:

Promise.try(function(){ 
    throw new Error("Something");
}).catch(function(err){
    console.log(err.message); // logs "Something"
});

通过超时(注意,我们必须返回Promise.delay):

With a timeout (note that we have to return the Promise.delay):

Promise.try(function() {
    return Promise.delay(1000).then(function(){
        throw new Error("something");
    });
}).catch(function(err){
    console.log("caught "+err.message);
});

通过一般的NodeJS功能可按:

With a general NodeJS funciton:

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

这方法是既快速又安全的捕捞,我推荐它,它使用很可能不是这里停留域下面的答案以上。

This approach is both fast and catch safe, I recommend it above the below answer which uses domains that are likely not here to stay.

我结束了使用领域,我已创建以下文件我称之为 mistake.js 包含以下code:

I ended up using domains, I have created the following file I called mistake.js which contains the following code:

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

它也可以像正常的捕捞同步code

It also works like normal catch for synchronous code

atry(function() {
    throw "something";
}).catch(function(err){
    console.log("caught "+err);
});

我想AP preciate上解决一些反馈

I would appreciate some feedback on the solution

在一个侧面说明,以V 0.8显然,当你赶在域中 process.on(uncaughtException)除外它仍然气泡。我处理这在我的 process.on(uncaughtException)

On a side note, in v 0.8 apparently when you catch the exception in the domain it still bubbles to process.on("uncaughtException"). I dealt with this in my process.on("uncaughtException") with

 if (typeof e !== "object" || !e["domain_thrown"]) {

不过,文档建议对 process.on(uncaughtException)任何

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

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