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);
});
}
.catch()at end will catch all errors occuring in athen()chain, afaik.