s3.getObject().createReadStream() : How to catch the error?

前端 未结 3 658
忘了有多久
忘了有多久 2021-01-03 18:29

I am trying to write a program to get a zip file from s3, unzip it, then upload it to S3. But I found two exceptions that I can not catch.

1.

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-03 18:50

    If you'd like to catch the NoSuchKey error thrown by createReadStream you have 2 options:

    1. Check if key exists before reading it.
    2. Catch error from stream

    First:

    s3.getObjectMetadata(key)
      .promise()
      .then(() => {
        // This will not throw error anymore
        s3.getObject().createReadStream();
      })
      .catch(error => {
        if (error.statusCode === 404) {
          // Catching NoSuchKey
        }
      });
    

    The only case when you won't catch error if file was deleted in a split second, between parsing response from getObjectMetadata and running createReadStream

    Second:

    s3.getObject().createReadStream().on('error', error => {
        // Catching NoSuchKey & StreamContentLengthMismatch
    });
    

    This is a more generic approach and will catch all other errors, like network problems.

提交回复
热议问题