Fetch async request and Error handling


I would like to know the logic behind the error handling in the following code (png format).

Why do 2 types of error handling coexist ? And what prevents the “throw new error” from being executed in case the value of (response.ok) is truthly.

Thanks a lot.

Ah this is lucky.
I’m doing the chapter on async error handling right now… so I’ll take a shot.

I think the "throw new Error(‘Request failed!’) should be inside an ] else [. So that would make it the if… else. Otherwise as you pointed out the error is always thrown.

I’m not sure what you mean by 2 types of error handling exist?

Here’s the lesson: https://www.codecademy.com/courses/javascript-errors-debugging/lessons/error-handling/exercises/try-catch-i

Hope this helps - again I just learned this so I could be off on the logic as well.

1 Like

Hello John,

Thanks for the link, i will look into it and try to find what the (those?) error statement(s) do(es) exactly.

It’s still not clear however what the “throw new Error” does and if it’s executed or not in the absence of error.

In the exercices that followed, we were only require “catch(error)” (and not throw new Error)…

Have a good one!

In the stuff in the lessons, there’s usually a return
in the part that would be there for
// Code to execute with jsonResponse
so they don’t bother doing an else,
because if response.ok is true (or truthy), and there’s no error, the code would reach the return and thus not execute anything after the if-statement block.


Good point, an implied return would make the code work. However, it is still unclear why in the boilerplate code they used “throw new Error” and what does throw new Error do, since in the lesson,

  1. most of the example functions are function that don’t return anything (no need to chain then statement with async, so no return needed in that case);
  2. none of the examle include a throw new Error

I think they have the “throw new error” there
to force the catch block to run … with the error with text 'Request Failed'.

I didn’t catch that at first that “return” ends the function so this definitely makes sense.
Thanks for sharing this great insight as I now will never wonder why there’s no else after a return in a conditional. :sweat_smile:

Also the same for the throw - you’re exactly right stops the function and goes to the nearest catch.

Ok so the only point of this throw new Error would be to have a personalized message (since an error would be raised even without it, considering all of the exercices that followed and that did not bother throwing an Error).

Thank you for your replies,

You may or may not get an error if you don’t throw one …
but its a good idea to have some output or something if the request failed (as in, request.ok is false),
so that if the problem is that the server didn’t send you the stuff you want,
you have some way to easily notice that.