[英]fetch and async/await without try/catch
我正在嘗試讓異步等待在沒有 try/catch 的情況下工作
return await fetch(url, options)
.then(res => res.json())
.catch(err => {
throw new Error(err)
})
這是我撥打電話的方式:
const response = await makeApiRequest('/reset', {
password: password1,
code
}, {
noauth: true
}).catch(err => {
debugger;
msg = err.message;
});
if (response) {
navigateTo('/');
}
問題是所有的 catch 塊都不起作用。 該代碼已過期並提供 401。
僅當無法發出請求時,獲取 API 才會失敗。 如果可以,即使狀態不好,fetch也會成功執行。
因為throw new Error(err)
從未被調用過,它只是在您嘗試將invalid string content
解析為 json object ( res.json()
) 時調用。 我來賓,在 401 情況下,您的服務器返回一個有效的 json 字符串,例如{message: "Unauthorized"}
,然后res.json()
工作正常,並且沒有拋出任何錯誤。
如果你想捕獲 http 錯誤,那么res
object 的http status code
是正確的方法:
return await fetch(url, options)
.then(res => {
if (res.status >= 300) { // error http status code range
throw new Error(res.status) // throw a error to the catch block
}
return res.json();
})
.catch(err => {
throw new Error(err) // catch and throw to the error of previous `.then` block
})
然后再試一次。
這就是我要工作的:
return fetch(url, options)
.then(async res => {
if (!res.ok) {
const err = await res.json()
throw err.message || res.statusText
}
return res.json()
})
.catch(err => {
throw new Error(err)
})
你可以這樣稱呼它:
const response = await myFetch('/forgot', {
email
}, {
headers: {
'x-contact': 'hello@puump.com'
}
}).catch(err => {
msg = err.message;
return;
});
if (response) {
push('/');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.