繁体   English   中英

Typescript(或Javascript)提取API异步/等待错误处理

[英]Typescript(or Javascript) Fetch API async/await error handling

我想使用async / awayt语法,Fetch API,并希望实现以下行为:

如果响应不是200,则记录响应,不扔任何东西并返回null。 如果响应为200,则返回响应。

但! 对于与404、505或200不同的所有内容,Fetch API都会引发异常,最后,我得到了一个像这样的丑陋构造:

...
try{
 let response = await fetch(url, {method: 'GET', mode: 'cors'});
 if(response.status != 200){
    console.log('Failed to get what I want, got status: ' + response.status);
    return null;
 }
catch(e){
  console.log('error bla bla');
  return null;
}
...

有没有更优雅的方法可以达到相同目的?

提取不会根据状态代码引发。 如果出现网络错误(例如无法访问服务器),它将抛出该错误。 这在Fetch规范中定义。

这是一个从Fetch获取各种状态代码的示例

 async function getit(status) { let url = 'https://httpstat.us/' + status try { let response = await fetch(url, { method: 'GET', mode: 'cors' }); if (response.ok) { console.log("Got what we wanted") } else { console.log('Failed to get what I want, got status: ' + response.status); } return "okay"; } catch (e) { console.log('A real error!'); return "network error"; } } getit(200).then(console.log) // error codes getit(400).then(console.log) getit(503).then(console.log) getit(401).then(console.log) 

只要它收到HTTP响应,就不应抛出。

(您的代码中确实有错别字-您丢失了if (response.status != 200) {右括号,但这应该导致语法错误,而不是被拒绝的诺言)

如果您愿意使用fetch()的替代方法,则axios似乎具有更干净/可配置的错误处理 实际上,默认设置完全符合您的用例。 (如果状态代码为2XX,则拒绝):

try {
    let response = await axios.get(url, {mode: 'cors'});
    return response;
} catch (error) {
    if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        console.log('Failed to get what I want, got status: ' + error.response.status);
    } else {
        console.log('error bla bla');
    }    
    return null;  
}

(顺便说一句,使用axios获取JSON只是一步,而对于r = await fetch() ,然后是r.json() ,则r.json()

MDN

当遇到网络错误或在服务器端未正确配置CORS时,fetch()承诺将以TypeError拒绝,尽管这通常意味着权限问题或类似问题,例如404并不构成网络错误。

和:

即使响应是HTTP 404或500,从fetch()返回的Promise也不会拒绝HTTP错误状态。相反,它将正常解析(ok状态设置为false),并且仅在网络故障或失败时拒绝。如果有任何事情阻止了请求的完成。

正如Garry在他的回答中所说,我建议创建一个中间件来处理不成功的响应,或者如果状态不是200或response.ok为false则抛出异常。

示例(使用https://httpstat.us/ ):

 async function getData() { try { let response = await fetch('https://httpstat.us/401', { method: 'GET', mode: 'cors' }); if (!response.ok) throw response.statusText; console.log('Dataaa'); return response } catch (e) { console.error(e); return null } } getData() 

我会说创建一个中间件,然后调用该中间件函数,例如fetch()。then(middleware)。 这样,它将始终针对每个请求使用中间件方法,您可以将支票添加到一个位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM