简体   繁体   English

当对象不存在时,headObject 从不抛出错误

[英]headObject never throws an error when object doesn't exist

I am currently trying to check if a file exists, using aws-sdk for Amazon s3 (More precisely, the function headObject).我目前正在尝试检查文件是否存在,使用 aws-sdk for Amazon s3(更准确地说,函数 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.正如我在任何地方都能读到的那样,这是在尝试检查文件是否存在时应该使用的函数(以便通过 getSignedUrl 获取其 URL),但是我无法使用它。

It seems that, no matter what I do, the function s3.headObject tells me that the object exists.似乎,无论我做什么,函数 s3.headObject 都会告诉我该对象存在。 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.使用此代码,“We are in the callback”从未出现,而“We are not in the callback”则正确出现。

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.根据我对函数应该如何工作的理解,如果文件不存在,它应该抛出一个错误(然后被我的捕获捕获),从而允许我不使用 getSignedUrl 函数创建错误的 URL。

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.如果您还有其他问题,我将非常乐意尽我所能回答。

This is the right way to check object existence using async / await syntax:这是使用async / await语法检查对象是否存在的正确方法:

// 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
  }
};

I do try out the syntex but it doesn't work.我确实尝试了 syntex,但它不起作用。 It is in my lambda function.它在我的 lambda 函数中。

params and params2 are predefined set of bucket and key. params 和 params2 是一组预定义的桶和键。

var url = s3.getSignedUrl('getObject', params);
    const objectExist = async (par) => { 
        try{
            console.log(s3.headObject(par).response); //I honestly couldn't find any 
            //section in the resoonse,
            // that make a DNE file different from a existing file.
             const ext = await s3.headObject(par).promise((resolve, reject) =>{
                  console.log("bbbbbbbbbbb");
                if(err) { // it keeps saying the err is not global variable. 
                //I am wondering why this is not defined.
                //Really had no idea of what else I could put as condition.
                    console.log("aaaa"); //never reach here.
                    return reject(false);}
                return resolve(true);
             });
             console.log(ext); //always true. 
             if(!ext){url = url = s3.getSignedUrl('getObject', params2, callback); }
            }catch(err){
                console.log("reeeeeeeeee"); //when the method failed it execute. 
                url = s3.getSignedUrl('getObject', params2, callback);
                console.log(url); //even though I am sure that params2 are valid key, but url in the log always returned undefined.
            }
      
  };
  objectExist(params);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 调用HeadObject操作时出现错误(404):Key“”不存在 - An error occurred (404) when calling the HeadObject operation: Key "" does not exist 错误:必须返回非空值,因为返回类型“Never”不允许 null。Never convertPlatformException(对象异常,StackTrace - Error: A non-null value must be returned since the return type 'Never' doesn't allow null. Never convertPlatformException(Object exception, StackTrace ClientError:调用HeadObject操作时发生错误(403):尝试上传视频时被禁止 - ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden when trying to upload video Collectstatic 失败 - botocore.exceptions.ClientError:调用 HeadObject 操作时发生错误 (404):未找到 - Collectstatic failing - botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found AWS CLI S3 调用 HeadObject 操作时发生客户端错误 (403):禁止访问 - AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden 尝试在 AWS Lambda Lambda function 中下载文件时如何修复“ClientError:调用 HeadObject 操作时发生错误(403):禁止” - how to fix "ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden" when trying to download file in AWS Lambda function botocore.exceptions.ClientError:调用 HeadObject 操作时发生错误 (403):在 AWS SageMaker 中使用本地模式时禁止 - botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden while using local mode in AWS SageMaker 当值不存在时,DynamoDBMapper 的查询方法返回什么? - What does DynamoDBMapper's query method return when value doesn't exist? Python 在 AWS Lambda 上给出甚至不存在的缩进错误 - Python in AWS Lambda giving indent error on line that doesn't even exist 无服务器框架错误:单个 API 网关项目 - API 网关 RestAPI 的 RootResourceId 属性<id>不存在</id> - Serverless Framework Error: Single API Gateway Project - RootResourceId attribute of API Gateway RestAPI <id> doesn't exist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM