Node.js Express中间件错误链

时间:2016-01-24 00:01:57

标签: node.js asynchronous express

我必须抓一个网页以获取一个密钥,以便以后用作cookie。那部分有效。但由于请求是异步的,因此不会处理错误。我想确保错误是通过中间件链传递的。但我无法理解这一点。谢谢你的帮助。

app.use('/', makeLoginCookie, function (req, res, next){
    console.log('My app.use() starts here.');
    //console.log('makeLoginCookie: %s', err);
    next(); 
});

这是函数

function makeLoginCookie(req, res, next) {
    httpOptions = {
        url: site.url,
        headers: {
            Cookie: null
        }
    }

// Get HIDDEN key, build login cookie
request(httpOptions, function(error, response, body) {
    if (!error && response.statusCode == 200) {
        //console.log(body)
        var match = body.match( /\<INPUT TYPE=HIDDEN id=\"key\", value=\"([0-9a-f]+)\"\>/i );
        var key = match[1]
        var encrypted = sha1(key + site.username + site.password);
        loginCookie = "username=" + key + ";password=" + encrypted;
        next();
    } else {
        console.log("Connect failed %s" , error);
        //err = new Error("Can't connect");
        next();
    }
  });
};

3 个答案:

答案 0 :(得分:1)

请参阅Express Error handling,您可以使用next(err);Express中传递错误。 Here是一个很好的链接。

答案 1 :(得分:0)

我会使用promises (Q library)来解决这个问题,也可以使用其他方法来解决这个问题。你的&#34; makeLoginCookie&#34;函数可以返回deferred.promise,当请求失败时,拒绝它并带有错误。

编辑1:我推荐这个精彩的视频,解释如何使用异步代码https://www.youtube.com/watch?v=obaSQBBWZLk正常工作。它可以帮助你解决这个问题和其他问题。

编辑2:使用promises就是这样,看看它是否对你有帮助:

var Q = require("q");

app.use('/', function (req, res, next) {

    // This part, we will call your function "makeLoginCookie"
    makeLoginCookie().then(function(){
        // This is called when your function RESOLVES the promise

        // Here you could log or do some stuff...

        // Then, go next...
        next();
    }, function(error){
        // This is called when your function REJECTS the promise
        console.log("Connect failed %s" , error);

        // And then, handle the error, like stopping the request and sending an error:
        res.status(400).json({errorMessage: error});
    })
}, function (req, res, next){
    console.log('My app.use() starts here.');
    next(); 
});

// Removed parameters from function
function makeLoginCookie() {
    // This is the object that will return a promise
    var deferred = Q.defer();

    httpOptions = {
        url: site.url,
        headers: {
            Cookie: null
        }
    }

    // Get HIDDEN key, build login cookie
    request(httpOptions, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            //console.log(body)
            var match = body.match( /\<INPUT TYPE=HIDDEN id=\"key\", value=\"([0-9a-f]+)\"\>/i );
            var key = match[1]
            var encrypted = sha1(key + site.username + site.password);
            loginCookie = "username=" + key + ";password=" + encrypted;

            // Instead of using next(), RESOLVE your promise
            // next();
            deferred.resolve(); // You can pass some data into it..
        } else {

            // Instead of using next(), REJECT your promise
            // next();
            deferred.reject(error); // You can pass some data into it, like an error object or string...
        }
    });

    // Promise that something will be fulfilled or reject later
    return deferred.promise;
};

答案 2 :(得分:0)

我的代码中的其他地方肯定存在一些错误,因为现在按预期工作。

} else {
    console.log("Connect failed %s" , error);
    err = new Error("Can't connect");
    next(err);
}