From 8907ece608276c073eb27df53f77746e6a204aa6 Mon Sep 17 00:00:00 2001 From: vicentematus Date: Mon, 24 Apr 2023 01:13:12 -0400 Subject: [PATCH] fix: throw known errors such as MethodNotAllowed, NotFoundError instead of 404 for kv assets --- .changeset/cool-foxes-battle.md | 4 ++ .../adapter-cloudflare-workers/files/entry.js | 39 +++++++++++++------ 2 files changed, 31 insertions(+), 12 deletions(-) create mode 100644 .changeset/cool-foxes-battle.md diff --git a/.changeset/cool-foxes-battle.md b/.changeset/cool-foxes-battle.md new file mode 100644 index 000000000000..dc40481d13c8 --- /dev/null +++ b/.changeset/cool-foxes-battle.md @@ -0,0 +1,4 @@ +--- +'@sveltejs/adapter-cloudflare-workers': minor +--- +return 404 for non-existent asset rather than throwing KVError diff --git a/packages/adapter-cloudflare-workers/files/entry.js b/packages/adapter-cloudflare-workers/files/entry.js index 0969ba1bbf07..8c8715f80c71 100644 --- a/packages/adapter-cloudflare-workers/files/entry.js +++ b/packages/adapter-cloudflare-workers/files/entry.js @@ -1,6 +1,11 @@ import { Server } from 'SERVER'; import { manifest, prerendered } from 'MANIFEST'; -import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler'; +import { + getAssetFromKV, + mapRequestToAsset, + MethodNotAllowedError, + NotFoundError +} from '@cloudflare/kv-asset-handler'; import static_asset_manifest_json from '__STATIC_CONTENT_MANIFEST'; const static_asset_manifest = JSON.parse(static_asset_manifest_json); @@ -86,19 +91,29 @@ export default { * @param {any} context */ async function get_asset_from_kv(req, env, context, map = mapRequestToAsset) { - return await getAssetFromKV( - { - request: req, - waitUntil(promise) { - return context.waitUntil(promise); + try { + return await getAssetFromKV( + { + request: req, + waitUntil(promise) { + return context.waitUntil(promise); + } + }, + { + ASSET_NAMESPACE: env.__STATIC_CONTENT, + ASSET_MANIFEST: static_asset_manifest, + mapRequestToAsset: map } - }, - { - ASSET_NAMESPACE: env.__STATIC_CONTENT, - ASSET_MANIFEST: static_asset_manifest, - mapRequestToAsset: map + ); + } catch (e) { + if (e instanceof NotFoundError) { + return new Response('Not found', { status: 404 }); + } else if (e instanceof MethodNotAllowedError) { + return new Response('Method not allowed', { status: 405 }); + } else { + return new Response('Internal Error', { status: 500 }); } - ); + } } /**