Unable to catch 403 in try-catch during fetch
Asked Answered
D

3

9

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;
  }
}
Doxy answered 22/9, 2018 at 15:54 Comment(1)
The code is ok. The problem cannot be replicated, stackblitz.com/edit/react-pb51rzBernie
C
11

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

Carbonic answered 22/9, 2018 at 16:4 Comment(1)
So there is no way I can catch this and display it to the user rather than it creating a log automatically?Doxy
S
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

Sulfaguanidine answered 16/2, 2020 at 13:49 Comment(0)
A
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;
  })
}
Adalineadall answered 22/9, 2018 at 16:5 Comment(1)
Do I add another catch after the last line? Since the .catch is inside the try itself.Doxy

© 2022 - 2024 — McMap. All rights reserved.