Reputation: 10888
I have got the following code:
export function fetchValueFromApi(){
return function act(dispatch){
dispatch(fetchingLimit);
return fetch('https://someapi/v1/foo/bar?api_key=123456789')
.then(response =>{
console.log("response",response.json());
response.json();
}).then(json =>{
if (json.data()) {
dispatch(receivingValue(json.data.result))
} else {
throw new Error('Error');
}
}).catch(error => dispatch(receivingValueFailed(error)))
}
}
Now I know this call won't succeed. I am expecting it to fail and go into the catch. However, I am getting this error:
Possible Unhandled Promise Rejection
So for some reason we're not hitting the .catch
.
How could I solve this?
Upvotes: 0
Views: 1628
Reputation: 664297
You're not return
ing the promises from your then
handlers, so there is no chaining. The response body is not even awaited. The catch
handler is not chained to the promise that actually rejects, therefore it the error is indeed unhandled.
export function fetchValueFromApi(){
return function act(dispatch){
dispatch(fetchingLimit);
return fetch('https://someapi/v1/foo/bar?api_key=123456789')
.then(response => {
var body = response.json();
console.log("response body", body);
return body;
// ^^^^^^
}).then(json => {
if (json.data ) {
// ^
return dispatch(receivingValue(json.data.result))
// ^^^^^^
} else {
throw new Error('Error');
}
}).catch(error =>
dispatch(receivingValueFailed(error))
)
}
}
Remember that arrow functions only implicitly return the expression value when you use the concise body syntax, i.e. without block braces.
Upvotes: 2
Reputation: 2925
So you are hitting the catch, just not with the error you expected.
The 403 is not an error as far as fetch is concerned, since the request itself was made successfully (the response is just not what your application expected). You have to handle 40X errors yourself. And as your console.log reveals, the exception happens before your throw new Error
is reached.
A fetch() promise will reject with a TypeError when a network error is encountered or CORS is misconfigured on the server side, although this usually means permission issues or similar — a 404 does not constitute a network error, for example.
From https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
You should
response.json()
in the first .then handler: .then(response => response.ok && response.json())
if (json && json.data)
Upvotes: 2