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

JavaScript Handling Errors

Tomasz Grodzki
Tomasz Grodzki
8,130 Points

Why do we need checkStatus function?

I have the same result in console log, regardless if there is checkStatus or not. So why do we need checkStatus?

2 Answers

Steven Parker
Steven Parker
229,732 Points

"checkStatus" provides a different response when an error occurs in fetching the data. If everything works OK, then the output is the same as it would be otherwise (intentionally).

Tomasz Grodzki
Tomasz Grodzki
8,130 Points

But I also get the same response even if there is an error (e.g. I mistyped the url). And there's no matter if I use .then(checkStatus) or not. The output in console log is the same when the error occurs. I also tested this directly on the code from the lesson.

Steven Parker
Steven Parker
229,732 Points

You might need to make a snapshot of your workspace and post the link to it here to allow the issue to be replicated. Make sure the "with" and "without" versions are easily identifiable in the snapshot.

Steven Parker
Steven Parker
229,732 Points

So with the error caused by the domain name, "checkStatus" does not run at all. But if you fix the domain name and create an error later in the path, it does run and issues the expected output.

I believe the difference is that an error in the domain causes the promise to reject, and that bypasses "then". But an HTTP error (as you get with something wrong later in the path) doesn't reject but instead resolves normally but with the "ok" status set to false. This is the situation that "checkStatus" is designed to handle.

For more details, see the explanation on the MDN page for Using Fetch.

Tomasz Grodzki
Tomasz Grodzki
8,130 Points

Now I see what's going on. Thanks for help!

Tomasz Grodzki
Tomasz Grodzki
8,130 Points

Version with checkStatus

And without checkStatus

I hope that these codes are identifiable enough. If I can improve sth to make this more readable, give me a sign.

Steven Parker
Steven Parker
229,732 Points

The one with the commenting was all I needed, great job! :+1: See the comment added to my answer.