I try to handle Unauthorized
error from server using redux-saga. This is my saga:
function* logIn(action) {
try {
const user = yield call(Api.logIn, action);
yield put({type: types.LOG_IN_SUCCEEDED, user});
} catch (error) {
yield put({type: types.LOG_IN_FAILED, error});
}
}
I fetch data like this:
fetchUser(action) {
const {username, password} = action.user;
const body = {username, password};
return fetch(LOGIN_URL, {
method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(body)
})
.then(res => {
res.json().then(json => {
if (res.status >= 200 && res.status < 300) {
return json
} else {
throw res
}
})
})
.catch(error => {throw error});
}
But anyway result is {type: 'LOG_IN_SUCCEEDED', user: undefined}
when I expect {type: 'LOG_IN_FAILED', error: 'Unauthorized'}
. Where is my mistake? How to handle errors right using Redux-Saga?
if you want to have that if statement verifying the response status
if(res.status >= 200 && res.status < 300) {
you need to have it inside your first promise where res is defined, it's currently inside the resolved promise forres.json()
If you need to make multiple API calls in one saga, the better approach is to throw errors at a fetch stage:
FETCH
SAGA
Don't handle the
then
anderror
in yourfetchUser
method and your saga. Since you are alreadytry
/catch
ing in your saga, you could handle it there.Example
Saga
Fetch
As a side note: I find
fetch
's api a little awkward because it returns athen
-able response when you make a request. There are many libraries out there; personally I preferaxios
which returns json by default.