Skip to content

Commit 141a8c5

Browse files
committed
fix: throw known errors such as MethodNotAllowed, NotFoundError instead of 404 for kv assets
1 parent 3a8195d commit 141a8c5

File tree

2 files changed

+31
-12
lines changed

2 files changed

+31
-12
lines changed

.changeset/cool-foxes-battle.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
---
2+
'@sveltejs/adapter-cloudflare-workers': minor
3+
---
4+
return known errors for non-existent asset rather than throwing KVError

packages/adapter-cloudflare-workers/files/entry.js

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import { Server } from 'SERVER';
22
import { manifest, prerendered } from 'MANIFEST';
3-
import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler';
3+
import {
4+
getAssetFromKV,
5+
mapRequestToAsset,
6+
MethodNotAllowedError,
7+
NotFoundError
8+
} from '@cloudflare/kv-asset-handler';
49
import static_asset_manifest_json from '__STATIC_CONTENT_MANIFEST';
510
const static_asset_manifest = JSON.parse(static_asset_manifest_json);
611

@@ -86,19 +91,29 @@ export default {
8691
* @param {any} context
8792
*/
8893
async function get_asset_from_kv(req, env, context, map = mapRequestToAsset) {
89-
return await getAssetFromKV(
90-
{
91-
request: req,
92-
waitUntil(promise) {
93-
return context.waitUntil(promise);
94+
try {
95+
return await getAssetFromKV(
96+
{
97+
request: req,
98+
waitUntil(promise) {
99+
return context.waitUntil(promise);
100+
}
101+
},
102+
{
103+
ASSET_NAMESPACE: env.__STATIC_CONTENT,
104+
ASSET_MANIFEST: static_asset_manifest,
105+
mapRequestToAsset: map
94106
}
95-
},
96-
{
97-
ASSET_NAMESPACE: env.__STATIC_CONTENT,
98-
ASSET_MANIFEST: static_asset_manifest,
99-
mapRequestToAsset: map
107+
);
108+
} catch (e) {
109+
if (e instanceof NotFoundError) {
110+
return new Response('Not found', { status: 404 });
111+
} else if (e instanceof MethodNotAllowedError) {
112+
return new Response('Method not allowed', { status: 405 });
113+
} else {
114+
return new Response('Internal Error', { status: 500 });
100115
}
101-
);
116+
}
102117
}
103118

104119
/**

0 commit comments

Comments
 (0)