我将获取 API 与 REST API 结合使用,我想全局处理某些错误,例如 500、503 ...
我试过这样做
function(url, method, data) {
return fetch(url, {
method: method || "GET",
body: JSON.stringify(data),
mode: "cors",
headers: {
"Content-Type": "application/json; charset=utf-8"
}
}).then(response => {
if (response.ok && response.status < 500) console.log("ouch");;
return response;
});
但似乎没有效果。 如何在获取 api 中捕获 500、503 ...
?
最佳答案
以这种方式尝试这种方法,您可以在一个地方处理所有可能的错误,您还可以生成自定义响应以返回,例如,如果您的所有请求都返回 JSON 数据,那么您可以在返回之前将响应转换为 JSON。
function secureFetch(url, method, data) {
return new Promise((resolve, reject) => {
fetch(url, {
method: method || "GET",
body: JSON.stringify(data),
mode: "cors",
headers: {
"Content-Type": "application/json; charset=utf-8"
}
}).then(response => {
// response only can be ok in range of 2XX
if (response.ok) {
// you can call response.json() here too if you want to return json
resolve(response);
} else {
//handle errors in the way you want to
switch (response.status) {
case 404:
console.log('Object not found');
break;
case 500:
console.log('Internal server error');
break;
default:
console.log('Some error occured');
break;
}
//here you also can thorow custom error too
reject(response);
}
})
.catch(error => {
//it will be invoked mostly for network errors
//do what ever you want to do with error here
console.log(error);
reject(error);
});
});
}
secureFetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));
secureFetch('https://jsonplaceholder.typicode.com/posts/100000000')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));
关于javascript - 获取 API 全局错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51297206/