admin管理员组

文章数量:1401122

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 !

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 !

Share Improve this question edited Sep 5, 2023 at 7:27 VLAZ 29.1k9 gold badges63 silver badges84 bronze badges asked Jan 19, 2018 at 11:14 Артем МирошниченкоАртем Мирошниченко 3392 gold badges7 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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
    });

本文标签: javascriptCatching error in fetch() functionStack Overflow