Skip to content

Commit

Permalink
Update error handling for downloading files from AWS
Browse files Browse the repository at this point in the history
  • Loading branch information
VadimKovalenkoSNF committed Jul 23, 2023
1 parent 9eea427 commit ac686f3
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 32 deletions.
61 changes: 34 additions & 27 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 12 additions & 4 deletions src/S3.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand, HeadBucketCommand } from '@aws-sdk/client-s3'
import * as logger from './Logger.js'
import { Readable } from 'stream'
import { publicIpv4 } from 'public-ip'

interface BucketParams {
Bucket: string
Expand Down Expand Up @@ -46,8 +47,13 @@ class S3 {

return this.bucketExists(this.bucketName)
.then(() => true)
.catch((err) => {
throw new Error(`Unable to connect to S3: ${err.message}`)
.catch(async () => {
throw new Error(`
Unable to connect to S3, either S3 login credentials are wrong or bucket cannot be found
Bucket used: ${this.bucketName}
End point used: ${s3UrlBase.href}
Public IP used: ${await publicIpv4()}
`)
})
}

Expand Down Expand Up @@ -97,10 +103,12 @@ class S3 {
} else reject()
})
.catch((err: any) => {
logger.log('S3 error while downloading file', err)
if (err && err.statusCode === 404) {
// For 404 error handle AWS service-specific exception
if (err && err.name === 'NoSuchKey') {
logger.log(`Error: The specified key ${key} does not exist.`)
resolve(null)
} else {
logger.log(`Error while downloading the file ${err}`)
reject(err)
}
})
Expand Down
3 changes: 2 additions & 1 deletion test/unit/s3.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ describeIf('S3', () => {
// Remove Image after test
await s3.deleteBlob({ Bucket: s3UrlObj.query.bucketName as string, Key: s3TestKey })

const imageNotExist = await s3.downloadBlob('bm.wikipedia.org/static/images/project-logos/polsjsshsgd.png')
// Image doesnt exist in S3
await expect(s3.downloadBlob('bm.wikipedia.org/static/images/project-logos/polsjsshsgd.png')).rejects.toThrow()
expect(imageNotExist).toBeNull()
})
})

0 comments on commit ac686f3

Please sign in to comment.