0

I would like to do some error handling on the response received from a call I am making and then move to the catch if the specific null check is hit. Something like this:

    fetch('example.json')
        .then(response => {
            if (response.data === null) {
                //go to catch
            }
        })
        .catch(error => {
            console.error("error happened", error);
        })

What would be the best way to go about doing something like this? Any red flags with throwing an error inside a then block?

6
  • if (response.data === null) { throw "Your error" } Commented Oct 26, 2020 at 11:32
  • You can wrap this function inside a promise and reject it if your condition is not satisfied. Commented Oct 26, 2020 at 13:50
  • im wondering also about the code practices too - is it weird to throw an error in a then block, it feels like i am throwing an axe into my foot so that i could use my medical insurance - i was hoping there was a way to check this response object without having to trigger the 'extreme' measure of throwing an exception. for example, 'continue' in a loop would gently move you to the next cycle, as opposed to doing 'break' and then writing another for loop. I am hoping for a more elegant way of doing this Commented Oct 26, 2020 at 14:11
  • @berlin - Re not having to trigger the 'extreme' measure of throwing an exception, I've updated my answer to give you an alternative. It has effectively the same outcome. (throw isn't really extreme in JavaScript, though.) Commented Oct 26, 2020 at 14:30
  • agreed - feels like javascript errors are much less significant than say, an error in java. was still hoping there'd be a chance for me to get by without explicitly throwing one Commented Oct 26, 2020 at 14:36

2 Answers 2

1

If you throw in a promise handler, that rejects the promise the handler returns. So:

fetch('example.json')
    .then(response => {
        if (response.data === null) {
            throw new Error();
        }
    })
    .catch(error => {
        console.error("error happened", error);
    })

What you throw will be the rejection reason the catch handler sees. It doesn't have to be an Error, but as with synchronous code, it's generally best if it is.

But, note that A) A fetch response doesn't have a data property, and B) You need to check for HTTP success and parse the JSON that was returned.

You probably want something like this:

fetch('example.json')
    .then(response => {
        if (!response.ok) {
            // (I tend to use an specialized `Error` type here
            // More on my anemic blog:
            // http://blog.niftysnippets.org/2018/06/common-fetch-errors.html)
            throw new Error("HTTP error " + response.status);
        }
        return response.json();
    })
    .then(data => {
        if (data === null) {
            throw new Error("The data is null");
        })
        // ...do something with `data`...
    })
    .catch(error => {
        console.error("error happened", error);
    });

In a comment on the question you've said:

i was hoping there was a way to check this response object without having to trigger the 'extreme' measure of throwing an exception

You do have an alternative which is basically identical in outcome: Return a rejected promise. Here's my second code block above adapted to do that:

fetch('example.json')
    .then(response => {
        if (!response.ok) {
            // (I tend to use an specialized `Error` type here
            // More on my anemic blog:
            // http://blog.niftysnippets.org/2018/06/common-fetch-errors.html)
            return Promise.reject(new Error("HTTP error " + response.status));
        }
        return response.json();
    })
    .then(data => {
        if (data === null) {
            return Promise.reject(new Error("The data is null"));
        })
        // ...do something with `data`...
    })
    .catch(error => {
        console.error("error happened", error);
    });

And as with the throw version, you don't have to use an Error, it's just best practice. It can be anything you want.

Sign up to request clarification or add additional context in comments.

1 Comment

great - thanks for the edit, i was hoping i could do something like this
0

If you want, you can throw an Error object from within your promise handler.

fetch('example.json')
  .then(response => {
    if (response.data === null) {
      throw new Error('oopsie');
    }
  })
  .catch(error => {
    console.error("error happened", error); // will show "Error: oopsie"
  })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.