2017-08-17 122 views
0

错误是Uncaught (in promise) Error: Not Found. 这似乎是由于窗口在自我内部不可用。自我既是服务人员又是窗口。新错误() - 未捕获(承诺)错误:未找到

下面的代码是在index.html中,一切工作正常。当网络请求返回404时,它将评估throwOnError并显示此错误。

var throwOnError = (response) => { 
    if (response.status >= 200 && response.status < 300 || response.status === 0) { 
     return response; 
    } 
    throw new Error(response.statusText); 
}; 

function cacheableRequestFailingToCacheStrategy({ event, cache }) { 
    return fetch(event.request) 
    .then(throwOnError) // do not cache errors 
    .then(response => { 
     cache.put(event.request, response.clone()); 
     return response; 
    }) 
    .catch(() => cache.match(event.request)); 
} 

function isRequestForStatic(request) { 
    return /.(png|jpg|jpeg|gif|css|js)$/.test(request.url); 
} 

function isSideEffectRequest(request) { 
    console.log(request.method); 
    return ["POST", "PUT", "DELETE"].includes(request.method); 
} 

function cacheFailingToCacheableRequestStrategy({ event, cache }) { 
    return cache.match(event.request) 
    .then(throwOnError) 
    .catch(() => fetch(event.request) 
     .then(throwOnError) 
     .then(response => { 
      cache.put(event.request, response.clone()); 
      return response; 
     }) 
    ); 
} 

function requestFailingWithNotFoundStrategy({ event }) { 
    return fetch(event.request) 
    .catch(() => { 
     const body = JSON.stringify({ error: "Sorry, you are offline. Please, try later." }); 
     const headers = { "Content-Type": "application/json" }; 
     const response = new Response(body, { status: 404, statusText: "Not Found", headers }); 
     return response; 
    }); 
} 

self.addEventListener("fetch", event => { 
    console.log(event.request); 
    if (isSideEffectRequest(event.request)) { 
    console.log("post", event.request.method); 
    event.respondWith(requestFailingWithNotFoundStrategy({ event })); 
    return; 
    } 

    if (isRequestForStatic(event.request)) { 
    event.respondWith(
     caches.open(CACHE_NAME) 
     .then(cache => cacheFailingToCacheableRequestStrategy({ event, cache })) 
    ); 
    return; 
    } 

    event.respondWith(
    caches.open(CACHE_NAME) 
     .then(cache => cacheableRequestFailingToCacheStrategy({ event, cache })) 
); 
}); 
+0

代码在我看来像是服务工作者,但你说“下面的代码在index.html中”。你能澄清吗? –

+0

另外:因为你有代码实际上产生“未找到”,并抛出'错误'对象,你实际上试图解决什么问题? –

+0

首先 - 这是服务人员...但我没有把它保存在单独的sw.js文件中。它在index.html中是全局服务工作者的范围。 –

回答

0

由于缺乏对预期行为的真实清晰度,我必须假设提问者希望在不抛出异常的情况下处理404错误。

一种选择是这样的(披露:它是由我写的),有缓存而已,网络首先,缓存第一个也是唯一网络战略的一个交钥匙服务的工作人员,对404不抛出错误:https://github.com/mohawk2/sw-turnkey

+0

是的,我想处理错误。但我不能抛出错误。因为服务人员自身内部不存在新的错误。我会研究你的解决方案 –

+0

根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error错误是自ECMA 1以来的标准JS。我相信它确实可用,并且“未找到”来自您自己的代码。 –

相关问题