17

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

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

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

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

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.

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?

4

1 回答 1

20

警告:我不会推荐使用域的原始答案,域将来会被弃用,我写原始答案很有趣,但我不再认为它太相关了。相反 - 我建议使用事件发射器和具有更好错误处理的承诺 - 这是下面的示例,而不是承诺。这里使用的承诺是Bluebird

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

使用一般的 NodeJS 功能:

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

这种方法既快速又安全,我推荐它在下面的答案之上,它使用可能不会留在这里的域。


我最终使用了域,我创建了以下我调用的文件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);
});

我将不胜感激有关解决方案的一些反馈

附带说明一下,在 v 0.8 中,当您在域中捕获异常时,它仍然冒泡到process.on("uncaughtException"). 我在我process.on("uncaughtException")的 with中处理了这个

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

但是,文档建议反对process.on("uncaughtException")任何方式

于 2013-01-13T13:43:08.473 回答