[英]Javascript not catching error using fetch
我有一個authService具有以下提取
export const handleForm = () => {
return fetch('http://localhost:5000/login')
.then(response => {
if (!response.ok) {
throw new Error("Email or password incorrect");
} else {
return response.json();
}
})
.then(json => json)
.catch(error => error);
};
我從控制器調用該方法:
form.onsubmit = function (e) {
handleForm(e)
.then(response => {
console.log(response);
//setAuthenticatedUser(response);
// setDomUser(response.user);
})
.catch(error => {
console.log(error);
document.querySelector('#error').innerHTML = error;
})
};
我已經嘗試了一些方法來在控制器中捕獲錯誤,但是我一直在觸發響應回調。 我的authService的錯誤沒有被捕獲
語法部分
p.catch(onRejected);
[...]
如果
onRejected
拋出錯誤或返回本身被拒絕的Promise,則catch()
返回的Promise將被拒絕; 否則,解決。
使用.catch(error => error)
作為回調返回異常。 因此,它既不會“拋出錯誤”,也不會“返回本身被拒絕的承諾”。 因此,它所返回的承諾得到了解決,而不是被拒絕。
只需刪除.catch(error => error)
就可以了。 當您使用它時,還請刪除.then(json => json)
因為它沒有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.