7

I'm making a put request using ReactJS, however, when I put in the wrong email/password combination, I get this logged on Chrome, even though I'm trying to catch all errors and show them in errorDiv:

enter image description here

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)
    });
    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;
  }
}
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Muhammad Ali
  • 3,478
  • 5
  • 19
  • 30

3 Answers3

9

As per the mdn, fetch will throw only when a network error is encountered.
404 (or 403) are not a network error.

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

a 404 does not constitute a network error, for example. An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true

Community
  • 1
  • 1
Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
7

I completely agree with @Sagiv, but there is a quick workaround to do that, although it is not a suggested way. Inside of try or promise.then(), you need to do this check.

const res = await fetch();
console.log(res);    // You can see the response status here by doing res.status

So, by some simple checks it is possible to resolve or reject a promise. For e.g. in your case

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;
  }
}

I strongly recommend using axios. For the fetch issue, you can refer to this link

1

This is because you throw Error and then catch part of your code does not execute. Try this:

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;
  })
}
Lazar Nikolic
  • 4,261
  • 1
  • 22
  • 46