{"message": "Internal Server Error"} 502

My friend and I are working on a new serverless function and are hitting quite a roadblock.

We are using serverless version 1.30.2, and have created a simple s3 fetchImages function and when running it we get a response 502.

I have seen multiple topics on how to properly format our response and send it through the callback, and maybe we are just stupid and are missing something… but this is not working as expected.

"use strict";

const AWS = require("aws-sdk");
const s3 = new AWS.S3();

module.exports.fetchImages = async (event, context, callback) => {
    const bucket = "cmedia";
    const path_to_folder = "/images/";
    const params = { Bucket: bucket, Delimiter: path_to_folder };

    s3.listObjects(params, function(err, data) {
        const message = err
        ? "Could not load objects from s3" + err
        : "Loaded " + data.Contents.length + " items from s3";

        const response = {
            statusCode: err ? 500 : 200,
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Credentials": true
            },
            body: JSON.stringify({
                message,
                gallery: data.Contents
            })
        };
        console.log(response);
        callback(null, response);
    });
};
Try with:

module.exports.fetchImages = async (event, context) => {
  const bucket = "cmedia";
  const path_to_folder = "/images/";
  const params = { Bucket: bucket, Delimiter: path_to_folder };

  const response = {
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Credentials": true
    }
  };

  try {
    const listedObjects = await s3.listObjects(params).promise();
    response.statusCode = 200;
    response.body: JSON.stringify({
      message: `Loaded ${listedObjects.Contents.length} items from s3",
      gallery: listedObjects.Contents
    });
    return response;
  } catch (e) {
    response.statusCode = 500;
    response.body: JSON.stringify({
      message: `Could not load objects from s3 ${err}`
    });
    return response;
  }
};

You can’t use callback if you’re handler function is async.

Of course You can, I have deployed async lambdas, that return callback and they are working.
I use callback, when I need to return non default status codes.

@SoftMaker The AWS Lambda docs only have two supported handler syntax

exports.myHandler = function(event, context, callback)

or

exports.myHandler = async function(event, context)

I did some testing to better understand how async handlers work with Node 8.10 and the only advice I can give is don’t do it. It’s not supported by AWS and will fail for most use cases.

Why do you need to use callback to return non default status codes? Anything you return will be treated as success. For failure you can just throw an Error. Are you trying to return a failure with a result?

It was the dang arrow function…

1 Like