【发布时间】:2019-07-10 16:18:03
【问题描述】:
上下文
对于我的fetch 请求之一(我在Vuex action 中使用,但这不是理解我的问题所必需的),我将从使用Promises 到async/await。
使用下面的代码,如果请求失败,我可以根据我的响应状态代码向最终用户提供错误消息。
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 来现场测试这个问题。随时更新。
【问题讨论】:
-
不使用
async / await..response.status等时完全一样 -
但是要和你的
thenable一样,你的const books想要在你的捕获中.. -
我试过了,但我无法在
await fetch()之后访问我的response.status,因为它直接进入了catch(exception)块,并且异常错过了响应数据。
标签: javascript error-handling async-await