Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

APIs Handling Errors

Saqib Ishfaq
Saqib Ishfaq
13,912 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,413 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,912 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

Caleb Waldner
Caleb Waldner
19,567 Points

Thank you for this. I had the exact question and this helped clear this up for me.