我正在使用expressjs,我有一条这样的路线:
router.route('/monitor')
.all(function (req, res, next) {
next();
}).get(monitor.monitorServers);
还有一个控制器(称为Monitor,具有上述路由器调用的monitorServers功能),这是控制器的完整代码:
var argv = require('minimist')(process.argv.slice(2));
var path = require("path");
var config = require(path.resolve(argv.conf));
var bunyan = require('bunyan');
var log = require(path.resolve('./lib/logger')).createLogger;
// create the S3 object
var AWS = require('aws-sdk');
var commonFunctions = require(path.resolve('./lib/functions-common'));
var async = require('async');
/**
* Monitor the different severs needed by the book server (check if they still running and connected to them)
* @param req
* @param res
*/
exports.monitorServers = function (req, res) {
// Redis Clients
var redisBs = commonFunctions.createRedisBS();
var redisMapi = commonFunctions.createRedisMapi();
var s3 = new AWS.S3();
// default values for the response
var status = 200;
var message = "Ok";
var errorMessage = "There's was an error in the book service, check the log to see which part";
async.waterfall([
/**
* Check Redis server of the book service
* @param callback
*/
function (callback) {
redisBs.on('ready', function (error) {
if (error) {
log.fatal({part: 'Redis'}, error);
}
if (!redisBs.connected) {
status = 500;
message = errorMessage;
log.fatal({part: 'Redis'}, 'Book service failed to connect to its Redis Server');
}
callback(null);
});
},
/**
* Check the redis server of Mapi
* @param callback
*/
function (callback) {
//REDIS MAPI
redisMapi.on('ready', function (error) {
if (error) {
log.fatal({part: 'Redis'}, error);
}
if (!redisBs.connected) {
status = 500;
message = errorMessage;
log.fatal({part: 'Redis Mapi'}, 'Book service failed to connect to Redis Mapi');
}
callback(null);
});
},
/**
* Check the S3 bucket connexion
*/
function () {
s3.headBucket({Bucket: config.bucketEnc}, function (error) {
if (error) {
status = 500;
message = errorMessage;
log.fatal({part: 'AWS S3'}, 'Book service failed to connect to AWS S3 bucket ' + error);
}
res.status(status);
res.json({book_service: message});
});
}
], function (err) { // in case of unexpected error
if (err) {
log.error("There was an error on monitoring " + err);
res.end();
}
});
};
响应已从控制器正确返回,但有时,即使我不调用路由,也会收到错误提示
发送标头后无法设置标头
在我放置
res.json({book_service: message});
的位置上引发了错误,您知道错误的根源在哪里吗? 最佳答案
您应该在success
的最终回调中处理failure
和async.waterfall()
大小写,而不是在waterwall过程的中间。
/**
* Check the S3 bucket connexion
*/
function (callback) {
s3.headBucket({Bucket: config.bucketEnc}, function (error) {
if (error) {
status = 500;
message = errorMessage;
log.fatal({part: 'AWS S3'}, 'Book service failed to connect to AWS S3 bucket ' + error);
callback(error);
}
// VERY IMPORTANT TO ENSURE WATERFALL PROCESS CAN FINISH!
callback(null, {book_service: message});
});
}
// Final callback of async.waterfall()
function (err, data) { // in case of unexpected error
if (err) {
log.error("There was an error on monitoring " + err);
res.end();
} else {
res.json(data);
}
}