APIs Handling Errors

Saqib Ishfaq
Saqib Ishfaq
13,911 Points

We mentioned .catch() in the fetchData() to handle the error when fetch fails,then whats point of this>>>

function checkStatus(data){
    if(response.ok){
        return Promise.resolve(response);
    } else {
        return Promise.reject(new Error(response.statusText));
    }
}

i understand whats happening here but don't get the point of it all.

1 Answer

Seth Kroger
Seth Kroger
56,318 Points

The thing here is that there are two different ways a fetch() call can "fail", but only one way that throws an exception. There are requests fail to be sent or get a response back from the server. Those will cause an exception, which catch() can catch. The second way is that the fetch() request gets a response back from the server, but the server sends back an error response such as 404 Not Found or 500 Internal Error. When this happens the fetch() is considered successful because it received valid response (an error response is still a response as far as fetch is concerned) and won't throw an error to be caught. But we still have to deal with the fact that we got an error code, and here we are throwing an error when we get one so the catch() will handle that case as well.

Saqib Ishfaq
Saqib Ishfaq
13,911 Points

ah thanks for the explaination, ok i get it, so just to confirm,

 .catch(error => console.log('looks like there was a problem', error))
// this is to throw error when server fails to respond or both when responds but not resolved

and this is >>

else {
        return Promise.reject(new Error(response.statusText));
//when server responds but its promise response is rejected and statusText is other than "ok"

Thanks again