From 1618391ee15556dee8f1a1e2b9336eae44fa8018 Mon Sep 17 00:00:00 2001 From: Pedro Cattori Date: Wed, 11 May 2022 18:06:09 -0400 Subject: [PATCH] refactor(@remix-run/deno): throw custom error when static files are not found so that `createRequestHandlerWithStaticFiles` is more portable across runtimes and adapters --- packages/remix-deno/server.ts | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/packages/remix-deno/server.ts b/packages/remix-deno/server.ts index cbb8791a4ab..18a246f3535 100644 --- a/packages/remix-deno/server.ts +++ b/packages/remix-deno/server.ts @@ -36,6 +36,12 @@ export function createRequestHandler({ }; } +class FileNotFoundError extends Error { + constructor(filePath: string) { + super(`No such file or directory: ${filePath}`); + } +} + export async function serveStaticFiles( request: Request, { @@ -64,9 +70,16 @@ export async function serveStaticFiles( headers.set("Cache-Control", defaultCacheControl(url, assetsPublicPath)); } - const file = await Deno.readFile(path.join(publicDir, url.pathname)); - - return new Response(file, { headers }); + const filePath = path.join(publicDir, url.pathname); + try { + const file = await Deno.readFile(filePath); + return new Response(file, { headers }); + } catch (error) { + if (error.code === "EISDIR" || error.code === "ENOENT") { + throw new FileNotFoundError(filePath); + } + throw error; + } } export function createRequestHandlerWithStaticFiles({ @@ -93,7 +106,7 @@ export function createRequestHandlerWithStaticFiles({ try { return await serveStaticFiles(request, staticFiles); } catch (error) { - if (error.code !== "EISDIR" && error.code !== "ENOENT") { + if (!(error instanceof FileNotFoundError)) { throw error; } }