即使使用500响应,使用h​​ttp.request的AWS Lambda方法也不会遇到错误事件

TLDR:如何在Lambda中logginghttp 500错误?

我正在尝试从我的内部API方法(不能直接访问SNS订阅)logging错误,并在CloudWatch中的Lambda中调用。 这是我在nodejs 6.10中的Lambda方法:

 var http = require('http'); exports.handler = function(event, context, callback) { var post_data = event.Records[0].Sns.Message; var post_options = { host: 'myhost.com', port: 80, path: '/path/to/api/', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': post_data.length } }; var post_request = http.request(post_options, function(res) { var body = ''; res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { callback(null, body);//This event happens, even when server returns 500 }); res.on('error', function(e) { callback(e);//This event never gets called }); }); post_request.on('error', function(e) { callback(e);//This event never gets called either }); post_request.end(post_data); }; 

我的API方法返回500.但是,我的post_request.on('error')res.on('error')事件永远不会执行。 它总是运行res.on('end')

我想在cloudwatch中报告完整的错误,但它只是给了我一个通用的错误消息,同时说lambda方法是成功的。

这是什么节点认为“错误”的一个怪癖。 就http库而言,没有错误。 它成功连接到你的API,并成功返回服务器给出的结果。 error handling程序只会触发TCP错误或重复响应。 如果你想要明智的行为,那么你需要检查响应的状态码。

 var post_request = http.request(post_options, function(res) { if (res.statusCode < 200 || res.statusCode > 299) // handle non-200 https errors; } // more code })