如何创建新的fetch Response promise以处理fetch请求彻底失败的场景
实现方案
你可以直接使用原生Response构造函数手动创建指定状态码的响应实例,在catch回调中直接返回该实例即可——Promise链中catch回调返回的普通值会自动被包装为resolved状态的Promise,下游可以直接通过then接收。
另外你的现有代码存在两个小问题需要修正:
myFunc的返回值类型标注错误,fetch返回的是Promise<Response>而非Response- 原代码的catch回调和函数末尾多了多余的闭合大括号
修正后的完整代码如下:
const myFunc = (): Promise<Response> => { return fetch('http://something') .then(r => { console.log('the call went through, the return code does not matter') return r }) .catch(err => { console.error(`ah crap, the call failed completely: ${err}`) // 手动创建503响应 return new Response(JSON.stringify({ error: '服务暂时不可用' }), { status: 503, statusText: 'Service Unavailable', headers: { 'Content-Type': 'application/json' } }) }) } myFunc().then(r => { // 无论请求成功失败都会走到这里,r为正常响应或手动构造的503响应 console.log('do something once myFunc is over') })
如果你不需要自定义响应体,也可以直接传null作为Response的第一个参数:
return new Response(null, { status: 503 })
内容的提问来源于stack exchange,提问作者WoJ
相关产品推荐
相关产品推荐

