首页 > 解决方案 > Workbox - 使用 setCatchHandler 时返回什么?

问题描述

在 Workbox docs (v5) 中,一个示例将发回Response.error()对象:

setCatchHandler(() => {
    return Response.error();
});

但是,我们需要支持一些没有响应 API 的移动设备——我应该使用什么来代替?

标签: workbox

解决方案


然后从handlerCallbackResponse返回的任何内容都按原样发送到主线程。

使用现有代码将任何响应作为错误处理的响应都应该有效。

这是Response.error()生成的内容:

Response {
  body: null
  bodyUsed: false
  headers: Headers {}
  ok: false
  redirected: false
  status: 0
  statusText: ""
  type: "error"
  url: ""
}

这是new Response(null, {status: 500})生成的:

Response {
  body: null
  bodyUsed: false
  headers: Headers {}
  ok: false
  redirected: false
  status: 500
  statusText: ""
  type: "default"
  url: ""
}

唯一的区别是status( 0 -> 500) 和type( 'error' -> 'default')。相同的最小差异适用于new Response(null, {status: 404})。另请注意,如果您使用的是 Fetch API,则带有错误状态的响应不会Response在被拒绝的 Promise 中解析,需要对'ok属性进行额外检查。

我通过Can I对不同平台使用不同的响应 API 的可用性进行了检查,但我发现它们并不准确。您可以在此处此处进行实时在线测试。Response,并且在所有最新的桌面和移动浏览器上都可用error()okstatus

另一种选择是使用这样的 polyfill Response它用包含实现的对象覆盖全局对象error(),但我对这种替代方案没有信心。


推荐阅读