![](/img/trans.png)
[英]How to properly use fetch .then/.catch or async await - Currency Exchanger example
[英]How to catch the status code when fetch fails using async await
语境
我将从使用Promises 异步/等待 获取请求之一(我在Vuex action中使用了该请求,但这对于理解我的问题不是必需的)。
使用以下代码,如果请求失败,我可以根据响应的状态代码向最终用户提供错误消息。
fetch("http://localhost:8000/api/v1/book", {
headers: {
Accept: "application/json"
}
}).then(response => {
if (!response.ok) {
if (response.status === 429) {
// displaying "wow, slow down mate"
} else if (response.status === 403) {
// displaying "hm, what about no?"
} else {
// displaying "dunno what happened \_(ツ)_/¯"
}
throw new Error(response);
} else {
return response.json();
}
}).then(books => {
// storing my books in my Vuex store
})
.catch(error => {
// storing my error onto Sentry
});
问题
使用async/await
,这就是我的代码现在的样子:
try {
const response = await fetch("http://localhost:8000/api/v1/book", {
headers: {
Accept: "application/json"
}
});
const books = await response.json();
// storing my books
} catch(exception) {
// storing my error onto Sentry
}
题
如果使用async/await
失败,如何确定响应返回的状态码?
如果我以错误的方式使用它,请不要犹豫,以更好的方式纠正我。
笔记
我做了一个JSFiddle来实时测试该问题。 随时更新。
这将与您的then
回调完全相同的代码:
try {
const response = await fetch("http://localhost:8000/api/v1/book", {
headers: {
Accept: "application/json"
}
});
if (!response.ok) {
if (response.status === 429) {
// displaying "wow, slow down mate"
} else if (response.status === 403) {
// displaying "hm, what about no?"
} else {
// displaying "dunno what happened \_(ツ)_/¯"
}
throw new Error(response);
}
const books = await response.json();
// storing my books
} catch(exception) {
// storing my error onto Sentry
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.