From 933bcbe7b4c54c3d185d9c5e6ae2c0eeda980b75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20=27rysiek=27=20Wo=C5=BAniak?= Date: Fri, 1 Mar 2024 18:23:23 +0000 Subject: [PATCH] handling 5xx HTTP errors directly in the service worker (ref. #36) --- plugins/fetch/index.js | 12 +++++------- service-worker.js | 25 +++++++++++++++++++++++-- 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/plugins/fetch/index.js b/plugins/fetch/index.js index d240e6f..5c1fa99 100644 --- a/plugins/fetch/index.js +++ b/plugins/fetch/index.js @@ -32,13 +32,11 @@ // run built-in regular fetch() return fetch(url, init) .then((response) => { - // 5xx? that's a paddlin' - // we do want to pass 3xx and 4xx on back to the client though! - if (response.status >= 500) { - // throw an Error to fall back to LibResilient: - throw new Error('HTTP Error: ' + response.status + ' ' + response.statusText); - } - // all good, it seems + + // we got something, it seems + // it might be a 2xx; it might be a 3xx redirect + // it might also be a 4xx or a 5xx error + // the service worker will know how to deal with those LR.log(pluginName, `fetched:\n+-- url: ${response.url}\n+-- http status: ${response.status} (${response.statusText})`); // we need to create a new Response object diff --git a/service-worker.js b/service-worker.js index 06e560f..a62484c 100644 --- a/service-worker.js +++ b/service-worker.js @@ -1045,7 +1045,18 @@ let libresilientFetch = (plugin, url, init, reqInfo) => { // starting the fetch... // if it errors out immediately, at least we don't have to deal // with a dangling promise timeout, set up below - let fetch_promise = plugin.fetch(url, init) + let fetch_promise = plugin + .fetch(url, init) + .then((response)=>{ + // 5xx? that's a paddlin' + // we do want to pass 3xx and 4xx on back to the client though! + if (response.status >= 500) { + // throw an Error to fall back to LibResilient: + throw new Error('HTTP Error: ' + response.status + ' ' + response.statusText); + } + // ok, we're good + return response + }) let timeout_promise, timeout_id [timeout_promise, timeout_id] = promiseTimeout( @@ -1256,7 +1267,7 @@ let getResourceThroughLibResilient = (url, init, clientId, useStashed=true, doSt }) // a final catch... in case all plugins fail .catch((err)=>{ - self.log('service-worker', "LibResilient failed completely: ", err, + self.log('service-worker', "all plugins failed: ", err, '\n+-- URL : ' + url) // cleanup @@ -1264,7 +1275,17 @@ let getResourceThroughLibResilient = (url, init, clientId, useStashed=true, doSt state: "failed", error: err }) + decrementActiveFetches(clientId) + + // print out all the errors from plugins in console for debugging purposes + self.log('service-worker', `request errored out:\n+-- url: ${reqInfo.url}\n+-- plugin errors:\n${ + reqInfo + .errors + .reduce((acc, cur)=>{ + return acc + ' ' + cur.join(': ') + '\n' + }, '')}`) + // rethrow throw err })