使用提取处理 500 响应 api
Handle a 500 response with the fetch api
我们对 fetch
进行了以下调用。
this.http.fetch('flasher', { method: 'post', body: jsonPayload })
.then(response => response.json())
.then(data => console.log(data));
这在我们收到 200 响应时有效,但在我们收到 500 响应时不向控制台记录任何内容。我们如何处理 500?
工作解决方案
将 then
与 catch
结合使用。
fetch('http://some-site.com/api/some.json')
.then(function(response) { // first then()
if(response.ok)
{
return response.text();
}
throw new Error('Something went wrong.');
})
.then(function(text) { // second then()
console.log('Request successful', text);
})
.catch(function(error) { // catch
console.log('Request failed', error);
});
详情
fetch()
returns 包含 Response
对象的 Promise
。 Promise
可以被满足或被拒绝。 Fulfillment 运行第一个 then()
,returns 它的承诺,然后运行第二个 then()
。拒绝抛出第一个 then()
并跳转到 catch()
.
参考资料
我们对 fetch
进行了以下调用。
this.http.fetch('flasher', { method: 'post', body: jsonPayload })
.then(response => response.json())
.then(data => console.log(data));
这在我们收到 200 响应时有效,但在我们收到 500 响应时不向控制台记录任何内容。我们如何处理 500?
工作解决方案
将 then
与 catch
结合使用。
fetch('http://some-site.com/api/some.json')
.then(function(response) { // first then()
if(response.ok)
{
return response.text();
}
throw new Error('Something went wrong.');
})
.then(function(text) { // second then()
console.log('Request successful', text);
})
.catch(function(error) { // catch
console.log('Request failed', error);
});
详情
fetch()
returns 包含 Response
对象的 Promise
。 Promise
可以被满足或被拒绝。 Fulfillment 运行第一个 then()
,returns 它的承诺,然后运行第二个 then()
。拒绝抛出第一个 then()
并跳转到 catch()
.