From 3bb5269b6f564d6cf49c4fe79a906179f3d3f891 Mon Sep 17 00:00:00 2001 From: Luke Hagar Date: Fri, 24 Jan 2025 15:06:21 -0600 Subject: [PATCH] feat: allow throwing error with `.response` prop in `upgrade` (#113) Co-authored-by: Pooya Parsa --- src/hooks.ts | 10 ++++++++-- test/fixture/_shared.ts | 14 +++++++++----- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/hooks.ts b/src/hooks.ts index 69e73e4..58a4a7b 100644 --- a/src/hooks.ts +++ b/src/hooks.ts @@ -66,8 +66,12 @@ export class AdapterHookable { }; } } catch (error) { - if (error instanceof Response) { - return { context, endResponse: error }; + const errResponse = (error as { response: Response }).response || error; + if (errResponse instanceof Response) { + return { + context, + endResponse: errResponse, + }; } throw error; } @@ -96,6 +100,8 @@ export type UpgradeRequest = headers: Headers; }; +export type UpgradeError = Response | { readonly response: Response }; + export interface Hooks { /** Upgrading */ /** diff --git a/test/fixture/_shared.ts b/test/fixture/_shared.ts index 077336d..9afe6c2 100644 --- a/test/fixture/_shared.ts +++ b/test/fixture/_shared.ts @@ -58,11 +58,15 @@ export function createDemo>( }, upgrade(req) { if (req.url.endsWith("?unauthorized")) { - return new Response("unauthorized", { - status: 401, - statusText: "Unauthorized", - headers: { "x-error": "unauthorized" }, - }); + throw { + get response() { + return new Response("unauthorized", { + status: 401, + statusText: "Unauthorized", + headers: { "x-error": "unauthorized" }, + }); + }, + }; } req.context.test = "1"; return {