在获取期间无法在尝试捕获中捕获403

时间:2018-09-22 15:54:10

标签: javascript reactjs put http-status-code-403 fetch-api

我正在使用ReactJS发出放置请求,但是,当我输入错误的电子邮件/密码组合时,即使我试图捕获所有错误并在{{1 }}:

enter image description here

errorDiv

3 个答案:

答案 0 :(得分:4)

根据mdnfetch仅在遇到网络错误时才会抛出。
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;
  }
}

我强烈建议您使用axios。对于获取问题,您可以参考此link

相关问题