mirror of
https://github.com/dergigi/boris.git
synced 2025-12-18 15:14:20 +01:00
fix: properly handle fetch errors in sw-dev.js
Fix scope issue where cachedResponse wasn't accessible in catch block. Now if fetch fails, we first check if we have a cached response and return it. If no cache exists, we let the error propagate so the browser can handle it gracefully.
This commit is contained in:
@@ -19,24 +19,26 @@ self.addEventListener('fetch', (event) => {
|
|||||||
event.respondWith(
|
event.respondWith(
|
||||||
caches.open('boris-images-dev').then((cache) => {
|
caches.open('boris-images-dev').then((cache) => {
|
||||||
return cache.match(event.request).then((cachedResponse) => {
|
return cache.match(event.request).then((cachedResponse) => {
|
||||||
if (cachedResponse) {
|
// Try to fetch from network
|
||||||
return cachedResponse
|
|
||||||
}
|
|
||||||
|
|
||||||
return fetch(event.request).then((response) => {
|
return fetch(event.request).then((response) => {
|
||||||
|
// If fetch succeeds, cache it and return
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
cache.put(event.request, response.clone())
|
cache.put(event.request, response.clone()).catch(() => {
|
||||||
|
// Ignore cache put errors
|
||||||
|
})
|
||||||
}
|
}
|
||||||
return response
|
return response
|
||||||
}).catch((error) => {
|
}).catch((error) => {
|
||||||
// If fetch fails (network error, CORS, etc.), return cached response if available
|
// If fetch fails (network error, CORS, etc.), return cached response if available
|
||||||
// or let the error propagate so the browser can handle it
|
if (cachedResponse) {
|
||||||
// Don't cache failed responses
|
return cachedResponse
|
||||||
return cachedResponse || Promise.reject(error)
|
}
|
||||||
|
// No cache available, reject the promise so browser handles it
|
||||||
|
return Promise.reject(error)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}).catch(() => {
|
}).catch(() => {
|
||||||
// If cache.open or match fails, try to fetch directly without caching
|
// If cache operations fail, try to fetch directly without caching
|
||||||
return fetch(event.request)
|
return fetch(event.request)
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user