1

I recently have learned something about fetch() and promise, and now I need to use it in project. Here I have a fetch() function, which works very well, but I think, it must catch an error. So, what is the best way to catch error in fetch() functions? And i need to catch them in both then()? Here some code:

const endpoint = 'http://localhost:3030/api/hotels';
const promise = fetch(endpoint)
   .then(res => res.json(), err => {
      console.log(err);
   })
   .then(parseRooms, err => {
      console.log(err);
   })

Thank you !

1 Answer 1

6

Use the fact that promise handlers chain together. Each call to then or catch creates a new promise, which is chained to the previous one.

So in your case:

const promise = fetch(endpoint)
    .then(res => res.json())
    .then(parseRooms)
    .catch(error => {
        // Do something useful with the error
    });

I'm assuming there that parseRooms throws an error if there's a problem with the structure it receives.

You probably want to check res.ok in there, too, since fetch only fails if there was a network error, not if there was an HTTP error such as a 404:

const promise = fetch(endpoint)
    .then(res => {
        if (!res.ok) {
            throw new Error(); // Will take you to the `catch` below
        }
        return res.json();
    })
    .then(parseRooms)
    .catch(error => {
        // Do something useful with the error
    });
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.