NodeJs AWS-SDK s3.upload upload function not throwing error as expected

Viewed 1292

I am using the following code to upload a file to s3

const AWS = require('aws-sdk'); // v2.712.0
AWS.config.update({ region: process.env.AWS_REGION });

async function upload(params)
{
    try 
    {
        await s3.putObject(params).promise();
    }
    catch(error)
    {
        console.log(error);
    }
}

const params = {...};// set params 
upload(params)

It works when credentials are correctly set. But if they are missing, error CredentialsError: Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1 will be thrown after minutes.

My questions are:

  • is my error handling correct?
  • is there a way to configure the SDK so that it throws this error immediately (at least a few seconds ) instead of waiting for minutes?

I have tried looking into the documentation and setting a lower timeout value (like a couple of seconds) in the httpOptions config but no luck.

Any help is appreciated. Thanks.

1 Answers

You need to await the function call on the last line to make sure that the invocation completes (either successfully or logs the error), e.g.

await upload(params);

Alternatively, you can use the promise construct, e.g.

upload(params)
  .then(data => { console.log('done', data); })
  // .catch(err => { console.log('error', err); })

The last line has been commented out since the upload() function already catches and logs the error internally. Personally, I would do error handling here instead. Or if the entire flow is as small as the example suggests, I would call the s3.putObject() function directly:

const AWS = require('aws-sdk');
AWS.config.update({ region: process.env.AWS_REGION });

const params = {...};
s3.putObject(params).promise()
  .then(data => { console.log('done', data); })
  .catch(err => { console.log('error', err); });
Related