I have created a simple function to authenticate users by their stored tokens, that function is based on a promise which returns a response with user details if it was successfully connected to our server API, if there's a server connection, it will return a promise rejection with specified error by React-native fetch method.
import React, { Component } from 'react';
import {
Text,
View,
AlertIOS,
} from 'react-native';
function AuthAPI(token)
{
return new Promise((resolve, reject) => {
fetch("https://myawesomeapi.com/auth", {
method: "POST",
body: '{"token": "' + token + '"}',
})
.then((response) => response.json())
.then((response) => {
resolve(response);
})
.catch((error) => {
reject(error);
});
});
}
export default class Home extends Component
{
constructor(props)
{
super(props);
this.state = {
bodyMessage: 'Waiting for response!',
};
}
componentWillMount()
{
AuthAPI("token-here")
.then((response) => {
const justAnotherVar = iamNotExist; // this will throw an error in next .catch
AlertIOS.alert("Your Name: " + response.userFullName);
this.setState({bodyMessage: 'Fetch is done with a response!'});
})
.catch((error) => {
console.err(error);
});
}
render()
{
const { bodyMessage } = this.state;
return (
<View style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text>Welcome..</Text>
<Text>{bodyMessage}</Text>
</View>
);
}
}
Problem explanation:
When there's an error inside AuthAPI.then(/***/)
, it will be caught by AuthAPI.catch
but as I understand AuthAPI.catch
will only catch errors returned by react-native fetch method errors from that promise rejection.
For example, inside AuthAPI.then
, I have assigned an undefined variable to a new constant variable const justAnotherVar = iamNotExist;
so that will throw an error in the next catch.
ReferenceError: Can't find variable: iamNotExist
What I want is to keep AuthAPI.catch
getting fetch method errors only and get regular red screen with specified error when there's an error inside AuthAPI.then(/***/)
I believe this is intended to happen, read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
What you can do is add a try/catch so the .then statement has it's own error handling and won't trigger the .catch when there's an issue:
AuthAPI("token-here")
.then((response) => {
try {
const justAnotherVar = iamNotExist; // this will throw an error in next .catch
AlertIOS.alert("Your Name: " + response.userFullName);
this.setState({bodyMessage: 'Fetch is done with a response!'});
} catch (e) {
//error handling
}
})
.catch((error) => {
console.err(error);
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments