-1

If .catch catches any errors upon request attempt, why would I need to use Throw Error... with .catch?

For instance, what is the throw Error used for, that the .catch doesn't handle automatically?

fetch(...).then((response) => {
        if (!response.ok) {
          throw Error(...)
        } else {
          response.json().then((responseData) => {
            ...
              }
            }
          })
        }
      }).catch(function (error) {
        console.error(error)
      })
  • Could you please give an example? I'm not sure what you're asking. – Dan Wilson Oct 9 '18 at 13:46
  • @DanWilson Updated with example – connected_user Oct 9 '18 at 13:51
  • Does the fetch function already check if (!response.ok) before fulfilling the Promise? – Greg Burghardt Oct 9 '18 at 16:33
2

if (!response.ok) { throw Error(...) gives you an opportunity to provide a specific error message when the response has a status code other than 200.

You could even switch on the status code and provide different messaging for 404 or 500 errors.

The lower .catch() is simple a catch-all for any exceptions that may occur while handling the response. If response.json() blows up due to some deserialization issue then .catch() will log an error to the console for you.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.