答案 0 :(得分:4)
根据mdn,fetch
仅在遇到网络错误时才会抛出。
404
(或403
)不是网络错误。
即使响应是HTTP 404或500,从fetch()返回的Promise也不会拒绝HTTP错误状态。相反,它将正常解析(ok状态设置为false),并且只会拒绝网络故障或是否有任何阻止请求完成的事情。
例如,404不构成网络错误。准确检查成功的fetch()包括检查已解决的诺言,然后检查Response.ok属性的值为true
答案 1 :(得分:1)
这是因为您引发错误,然后捕获部分代码未执行。试试这个:
async connect(event) {
try {
const userObject = {
username: this.state.userName,
password: this.state.password
};
if (!userObject.username || !userObject.password) {
throw Error('The username/password is empty.');
}
let response = await fetch(('someurl.com'), {
method: "PUT",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(userObject)
}).then(response => {
response.json();
console.info(resJSON.message);
console.info(resJSON.message.auth_token);
window.location = "/ledger/home";
}).catch(e => {
document.getElementById("errorDiv").style.display = 'block';
document.getElementById("errorDiv").innerHTML = e;
})
}
答案 2 :(得分:1)
我完全同意@Sagiv,但是有一个快速的解决方法,尽管这不是建议的方法。 在try或promise.then()内部,您需要执行此检查。
const res = await fetch();
console.log(res); // You can see the response status here by doing res.status
因此,通过一些简单的检查,可以解决或拒绝承诺。例如就您而言
async connect(event) {
try {
const userObject = {
username: this.state.userName,
password: this.state.password
};
if (!userObject.username || !userObject.password) {
throw Error('The username/password is empty.');
}
let response = await fetch('someurl.com', {
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(userObject)
});
if (response.status === 403) throw new Error('403 is unacceptable for me!');
let resJSON = await response.json();
if (!response.ok) {
throw Error(resJSON.message);
}
console.info(resJSON.message);
console.info(resJSON.message.auth_token);
window.location = '/ledger/home';
} catch (e) {
document.getElementById('errorDiv').style.display = 'block';
document.getElementById('errorDiv').innerHTML = e;
}
}