skip to Main Content

I’m just learning React, so if my questions are a bit naive, sorry for that

Currently I’m creating a small React app, which fetch news via api and display them with some additional features

The problem I faced, is that I cannot catch error (error.status etc.) if my fetch failed

I tried to add .catch block and catch the error, but somehow it doesn’t work for me, the next question which comes – how to redirect to Error page in case of rejected promise, is it possible to do in fetch function directly?

Here is the fetch function:

 function getSearchResult() {     
    fetch(apiUrl)
      .then(res => res.json())
      .then(data => setSearchResult(data))
    }

If I got data, everything works fine, however, I cannot make any progress with error handling

3

Answers


  1. You can use async await syntax

    async function getSearchResult() {  
      let response;
      try {
         response = await fetch(apiUrl)
      } catch(error) {
         console.log('error')
      }
    
      if (response?.ok) {
        const data = await response.json()
        setSearchResult(data)
      } else {
        console.log(`error code: ${response?.status}`)
      }   
    }
    

    Async await is more clean but if you don’t want the above syntax you can try this

    function getSearchResult() {     
      fetch(apiUrl)
      .then(res => {
        if (res.status >= 200 && res.status <= 299) {
          return res.json()
        } else {
         // You can redirect to error page here or show an error toast
         throw Error('Error message');
        } 
       })
      .then(data => setSearchResult(data))
      .catch((error) => {
       console.log(error);
      })
    }
    
    Login or Signup to reply.
  2. Method 1:

    You can add .catch() after the .then():

    function getSearchResult() {
        fetch(apiUrl)
          .then(res => res.json())
          .then(data => setSearchResult(data))
          .catch(error => {
              // Do something on error 
              console.log(error)
          })
    }
    

    Method 2:

    Use try & catch instead.

    async function getSearchResult() {
        try {
            const request = await fetch(apiUrl)
            const data = await request.json()
            setSearchResult(data)
        }
        catch(error) {
            // Do something on error 
            console.log(error)
        }
    }
    
    Login or Signup to reply.
  3. try this try catch block please

    try {
    
      let response = fetch(apiUrl);
      console.log(response .data);
    }catch (error) {
      if (error.response) {
          console.log(error.response)
      }
      else if (error.request)
          console.log(error.request);
      else
          console.log(error.message);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search