Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get axios Response object when error occurred with Redux Saga

This is new for me and I try to figure out how to retrieve the request body when an error occurred with axios using yield generator (redux-saga)

Here is the piece of code I'm using:

function requestLogin(user: ILoginUserPayload) {
  const loginUrl = `${config.apiUrl}/auth/logIn`;
  return axios.post(loginUrl, user);
}

export default function* watchAuthAction(): IterableIterator<any> {
  while (true) {
    const { payload }: { payload: ILoginUserPayload} = yield take(TYPES.LOGIN_REQUEST);

    console.log(`Payload`, payload);
    try {
      const response = yield requestLogin(payload);
      console.log(`Response`, response);
    } catch (error) {
      // According to my debug, error.request contains all the axios info
      console.log(error.request.response);
      yield put({ type: TYPES.LOGIN_FAILURE, error: error.request.response.message });
    }
  }
}

I used VSCode to debug the error content and I found out it has the axios request information (I mean, I 'm 99% sure that axios throw an error and it comes here)

My body response looks like that:

{"message":"User doesn't exist","stack":"Error: User doesn't exist"}

So I try to get it with:

console.log(error.request.response.message);

But it doesn't work, maybe I forget something about axios...

Any idea?

Edit: I'm actually reading this part: https://github.com/axios/axios#handling-errors But I still can't reach my data :/

like image 899
Vincent Avatar asked Jul 22 '18 10:07

Vincent


1 Answers

Your code seems to be about right, only difference for me is this:

try {
    const response = yield call(apiCall, action.payload)
      yield put({ type: successReducer, payload: response });
  } catch(error) {
    // Construct an error message
    let errorMessage = error.response.status + ":"+ error.response.statusText;
    yield put({ type: failReducer, payload: {  message : errorMessage }});
  }

So to me the difference seems to be that I access error.response.status instead of error.request.response.

like image 181
Jannunen Avatar answered Sep 18 '22 11:09

Jannunen