How to catch error when Backendless return empty array to axios - react native

346 Views Asked by At

I have a React-Native code that retrieves a data of REST API from backEndless.

In some cases, the data is an empty array. My code return this error:

error [TypeError: undefined is not an object (evaluating 'res.data[0]['ownerId']')]

It means the the AXIOS ENTER the .then part in stead of entering .catch part, it accepts the empty array as a result.

What should I get is Request Failed with code 401, but I can't catch the error.

any help?

here is my code:

export const confirmCode = (phone,code)=>{
    return (dispatch,getState)=>{
        dispatch(confirmCodeStart());
        phone = phone.substring(2);
        console.log(''+code+':'+phone+'');


        axios.get('/data/Auth?where=code='+code+'&phone='+phone+'')
           .then((res) =>{
               
               console.log(res.status);
               console.log('entereeeeed');
                ownerid = res.data[0]['ownerId'];
            
            
               
               
               //console.log(res.data[0]['ownerId']+"aaaaa");
               //getUser(res.data[0]['ownerId'],phone,props);
               ////////
               
                    //api request
                    axios.post('/users/login',{'objectId':ownerid})
                    .then(res2=>{
                        dispatch(confirmCodeSuccess());
                        //console.log(res.data);
                        userToken=res2.data['user-token'];
                        userData=res2.data;
                        console.log(res2.data);
                        //const {token,user} = res2.data;????????
                        axios.defaults.headers.Authorization ='Bearer '+userToken;
                        //dispatcher.dispatch({type:'SET_TOKEN',payload:{token:userToken}});
                        //dispatcher.dispatch({type:'SET_USER',payload:{user:userData}});
                        dispatch(setToken(userToken));
                        dispatch(setUser(userData));
                        AsyncStorage.setItem(TOKEN_KEY,userToken);
                        AsyncStorage.setItem(USER_KEY,JSON.stringify(userData));
                        
                        
                    })
           })
           .catch(error=>{
            Reactotron.log('error',error);
               console.log('error',error);
               dispatch(confirmCodeFailure());
               
           })     
    };
};
1

There are 1 best solutions below

3
AliReza Beigy On

You should throw to move compiler to catch part

...

        axios.get('/data/Auth?where=code='+code+'&phone='+phone+'')
           .then((res) =>{
               if(!res.data) {
                  throw res
               }
               
               console.log(res.status);
               console.log('entereeeeed');
                ownerid = res.data[0]['ownerId'];
...

when you throw inside the then section compiler goes to the nearest catch section

I make following example to my friend to understand promise work flow

new Promise(function(resolve, reject) {
  setTimeout(() => reject(true), 1000);
}).then(() => {
console.log("heh1")
throw true
}).catch(() => {
console.log("heh2")
}).then(() => {
console.log("heh3")
throw true
}).then(() => {
console.log("heh4")
}).then(() => {
console.log("heh5")
}).catch(() => {
console.log("heh6")
})

Result:

heh2
heh3
heh6