Skip to content

Commit 50bf74c

Browse files
committed
fix: handle NotFound exception correct
1 parent 6bd161a commit 50bf74c

File tree

1 file changed

+38
-16
lines changed

1 file changed

+38
-16
lines changed

src/index.ts

Lines changed: 38 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
DeleteObjectCommand,
33
GetObjectCommand,
44
HeadObjectCommand,
5+
NotFound,
56
PutObjectCommand,
67
S3Client,
78
} from "@aws-sdk/client-s3";
@@ -36,12 +37,21 @@ export const exists = async (
3637
path: string,
3738
): Promise<boolean> => {
3839
const client = new S3Client(bucket.connection);
39-
const res = await client.send(
40-
new HeadObjectCommand({
41-
Bucket: bucket.name,
42-
Key: path,
43-
}),
44-
);
40+
const res = await client
41+
.send(
42+
new HeadObjectCommand({
43+
Bucket: bucket.name,
44+
Key: path,
45+
}),
46+
)
47+
.catch((err) => {
48+
if (err instanceof NotFound) {
49+
return {
50+
ContentLength: undefined,
51+
};
52+
}
53+
throw err;
54+
});
4555

4656
return res.ContentLength !== undefined;
4757
};
@@ -51,24 +61,36 @@ export const get = async (
5161
path: string,
5262
): Promise<Buffer | null> => {
5363
const client = new S3Client(bucket.connection);
54-
const res = await client.send(
55-
new GetObjectCommand({
56-
Bucket: bucket.name,
57-
Key: path,
58-
}),
59-
);
64+
const res = await client
65+
.send(
66+
new GetObjectCommand({
67+
Bucket: bucket.name,
68+
Key: path,
69+
}),
70+
)
71+
.catch((err) => {
72+
if (err instanceof NotFound) {
73+
return null;
74+
}
75+
throw err;
76+
});
6077

61-
return res.Body ? Buffer.from(await res.Body.transformToByteArray()) : null;
78+
return res?.Body ? Buffer.from(await res.Body.transformToByteArray()) : null;
6279
};
6380

6481
export const deleteFile = async (
6582
bucket: Bucket,
6683
path: string,
6784
): Promise<void> => {
6885
const client = new S3Client(bucket.connection);
69-
await client.send(
70-
new DeleteObjectCommand({ Bucket: bucket.name, Key: path }),
71-
);
86+
await client
87+
.send(new DeleteObjectCommand({ Bucket: bucket.name, Key: path }))
88+
.catch((err) => {
89+
if (err instanceof NotFound) {
90+
return;
91+
}
92+
throw err;
93+
});
7294
};
7395

7496
export const getStreamed = async (

0 commit comments

Comments
 (0)