0
votes

Below code is making ajax request and getting data. As you can see then((response) => response.json()) is to convert response to json. But what if the http status is unauthorized or something else (400, 401 etc) and no json data is returned. Is there any better way to check status code before I convert the response to json?

I guess the catch is where I can do this, however, I want to keep catch for unhandled exceptions. Based on the status code I would like to show exact error user received(of course not for login component for security reasons). For example, Invalid Authorization, Invalid token.

My fetch code looks like this:

onLoginPressed() {

    fetch('http://localhost:8080/api/user/login', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            username: this.state.username,
            password: this.state.password
        })
    }).then((response) => response.json())
        .then((responseJson) => {

            if (responseJson.status === 500) {
                Alert.alert(responseJson.message);
            } else if(responseJson.profileCompleted == false){
                this.props.navigation.navigate('SetupOne');
            } else {
                this.props.navigation.navigate('Home');
            }

        }).catch((error) => {
        console.error(error);
    });
}
1
.catch() at end will catch all errors occuring in a then() chain, afaik. - Chris G
@ChrisG - Updated question. - VK321

1 Answers

3
votes

If you look at the docs for fetch, you will see this:

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.

And further down:

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.

So in other words, if this concerns you, you might want to check the status first, before doing your json body conversion. Something like the following:

const handleResponse = res => {
  if(res.ok) {
    return res.json()
  }
  throw new Error('Network response was not ok.')
}

fetch(someUrl, details)
  .then(handleResponse)      
  .then(doYourWorkWithJSON)
  .catch(err => console.error(err))