Ad

HeadObject Never Throws An Error When Object Doesn't Exist

- 1 answer

I am currently trying to check if a file exists, using aws-sdk for Amazon s3 (More precisely, the function headObject).

As I could read literally everywhere, this is the function that is supposed to be used when trying to check if a file exists (In order to then get its URL through getSignedUrl), however I can't bring it to work.

It seems that, no matter what I do, the function s3.headObject tells me that the object exists. I tried checking for existing items, non-existing items, and even in non-existing buckets : All of these got me the exact same output. I tried different ways of calling the function (Async or not, using its callback or not), but no difference.

Here is how I realize my call to the function :

var params = {
    Bucket: 'BUCKET NAME',
    Key: ""
}

// Some more code to determine file name, confirmed working

params.Key = 'FILE NAME'
try {
    s3.headObject(params)
    // Using here the file that is supposed to exist
} catch (headErr) {
    console.log("An error happened !")
    console.log(headErr)
}

I also tried using a callback : However, it seems that said callback was never entered. Here is what my code looked like :

var params = {
    Bucket: 'BUCKET NAME',
    Key: ""
}

// Some more code to determine file name, confirmed working

params.Key = 'FILE NAME'
s3.headObject(params, function(err: any, data: any) {
    console.log("We are in the callback")
    if (err) console.log(err, err.code)
    else {   
    // Do things with file
    }
})
console.log("We are not in the callback")

With this code, "We are in the callback" never appeared, while "We are not in the callback" was correctly appearing.

No matter what I do, no error is ever caught. From what I understand from how the function is supposed to work, in case the file doesn't exist, it is supposed to throw an error (Then caught by my catch), thus allowing me not to create false URLs with the getSignedUrl function.

What am I doing wrong here ?

Thank you all for your answers. If you have additional questions, I'll be more than glad to answer the best I can.

Ad

Answer

This is the right way to check object existence using async/await syntax:

// Returns a promise that resolves to true/false if object exists/doesn't exist
const objectExists = async (bucket, key) => {
  try {
    await s3.headObject({
      Bucket: bucket,
      Key: key,
    }).promise(); // Note the .promise() here
    return true; // headObject didn't throw, object exists
  } catch (err) {
    if (err.code === 'NotFound') {
      return false; // headObject threw with NotFound, object doesn't exist
    }
    throw err; // Rethrow other errors
  }
};
Ad
source: stackoverflow.com
Ad