From 636353b7d36a265be625dc802e52cd06b02b53f5 Mon Sep 17 00:00:00 2001 From: flakey5 <73616808+flakey5@users.noreply.github.com> Date: Wed, 27 Sep 2023 10:53:16 -0700 Subject: [PATCH] src: return message and stack trace on unhandled error in dev --- src/env.ts | 4 ++++ src/worker.ts | 33 +++++++++++++++++++++++---------- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/src/env.ts b/src/env.ts index d8f926a..2d8b418 100644 --- a/src/env.ts +++ b/src/env.ts @@ -1,4 +1,8 @@ export interface Env { + /** + * Environment the worker is running in + */ + ENVIRONMENT: 'dev' | 'staging' | 'prod'; /** * R2 bucket we read from */ diff --git a/src/worker.ts b/src/worker.ts index b140baf..1ec3733 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -13,16 +13,29 @@ interface Worker { const cloudflareWorker: Worker = { fetch: async (request, env, ctx) => { const cache = caches.default; - switch (request.method) { - case 'HEAD': - case 'GET': - return handlers.get(request, env, ctx, cache); - case 'POST': - return handlers.post(request, env, ctx, cache); - case 'OPTIONS': - return handlers.options(request, env, ctx, cache); - default: - return responses.METHOD_NOT_ALLOWED; + try { + switch (request.method) { + case 'HEAD': + case 'GET': + return handlers.get(request, env, ctx, cache); + case 'POST': + return handlers.post(request, env, ctx, cache); + case 'OPTIONS': + return handlers.options(request, env, ctx, cache); + default: + return responses.METHOD_NOT_ALLOWED; + } + } catch (e) { + let responseBody = 'Internal Server Error'; + + if (env.ENVIRONMENT === 'dev' && e instanceof Error) { + responseBody += `\nMessage: ${e.message}\nStack trace: ${e.stack}`; + } + + return new Response(responseBody, { + status: 500, + headers: { 'cache-control': 'no-store' }, + }); } }, };