$ cat handler.js
'use strict';
var AWS = require('aws-sdk');
AWS.config.region = 'ap-southeast-1';
module.exports.hello = (event, context, callback) => {
var s3 = new AWS.S3();
s3.listObjectsV2({ Bucket: "BLAH-BLAH-TRIGGER-AN-ERROR", Prefix: "movies/" }, (err, data) => {
if (err) {
callback(err, null)
} else {
console.log(data)
}
callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
});
};
$ serverless invoke local -f hello
{
"errorMessage": "The specified bucket does not exist",
"errorType": "Error"
}
{
"message": "Go Serverless v1.0! Your function executed successfully!",
"event": ""
}
I don’t want ‘Go Serverless v1.0! Your function executed successfully!’ to run. I just want the function to end. How should I be going about it? Many thanks,
Importantly, calling callback() doesn’t terminate your Lambda function. From what I can tell it just set the response that will be sent to the caller once your function terminates.
I know this is old, but I’m fairly confused here. I have the same logic going on an APIGateway, with this exact pattern (of course the result is not null, but an API response.)
It works when I invoke locally with a mock API request JSON file, but fails with an internal server error when deployed to AWS. I know it is related to this statement because if I get rid of the return, the rest of the function executes. With the return statement, it fails with no errors, just exits (due to the return.) It seems like the callback just isn’t being executed because of the return.
@freako987 Are you using Node 8.10? Have you declared your handler async? If so you can’t use callback and need to return a value. I wrote an article explaining how async appears to work with Node 8.10 How async Lambda handlers work in Node 8.10
Migrated to 8.10 recently, cannot use return callback(null, response); nor callback(null, response); return.
In the doc, it implies that callback is supported, but that is not the case whenever I try to push my lambda with my serverless command.
I created a new callback function on my lambda console and set the environment to node 8.10, it worked as expected. I use similar function on serverless project, I see this Task timed out after 6.01 seconds on my cloudwatch log.