0

I'm pretty new on React and I'm learning this language nowadays. For this purpose I'm building a test project on which I try to encounter the main classical issues and looking to solve it.

For most of React developpers, there are no difficulties in following code but I will give a few details for better comprenhension.

I have a portion of javascript code that is returning a list of articles from a Symfony Backend API only if user is authorized for getting it (Authorization via JWT will be done later). A getArticles function returns a Promise that tries to get the articles from the Symfony backend inside a try {} catch (error) {} block.

Voluntarily, Authorization token is not send to trigger an error in the query.

As the axios.get is located inside a try {} catch (error) {} block, I am surprised that an error appears in the console for the request. It doesn't impact the behavior but it is not very clean to have these errors in the console.

My question(s) : Why an error appears in the console while the code is inside a try/catch ? To get a cleaner app behavior, is there a way to avoid having this error in the console ? I have found other React try/catch issues but I didn't deduct the similarity with my issue. Am I missing something ?

Thanks in advance ;-)

I am aware that my code could be refactored, do not hesitate to suggest any good practice

componentDidMount(){
        /*To be prepared to attach JWT token*/
        axios.interceptors.request.use(req => {
          return req;
        });

        const getArticles = async() => { return new Promise( (resolve, reject)=> { 
                try{
                    const data = axios.get('https://xxxxx/api/articles');
                    resolve(data);
                } catch (err) {
                    reject(err);
                }
            });
        }
          
        getArticles().then(res => {
            const articles = res.data.data.items;
            this.setState( {errorOnArticlesLoading:false, articles: articles } );
        })
        .catch(error => {
            this.setState( {errorOnArticlesLoading:true} );
        });
}
Grégory C
  • 419
  • 2
  • 7
  • 23
  • Because you're resolving the promise before the Axios call does anything. It should be `const data = await axios.get(...)` and remove the extra `new Promise` wrapper and just `return data` (don't mix `await/async` with "normal" promises.) – Guy Incognito Oct 31 '20 at 12:09

2 Answers2

0

It seems that there are no solutions to avoid the 401 http error code in the console because it it printed by Chrome itself: See discussion here. So the following code cannot avoid the 401 error status to be printed in the console.

componentDidMount(){
        /*To be prepared to attach JWT token*/
        axios.interceptors.request.use(req => {
            return req;
        });
          
        const getArticles = async() => { 
                const data = await axios.get('https://xxxx/api/articles');
                return data;
        }
          
        getArticles().then(res => {
            const articles = res.data.data.items;
            this.setState( {errorOnArticlesLoading:false, articles: articles } );
        })
        .catch(error => {
            this.setState( {errorOnArticlesLoading:true} );
        });
}
Grégory C
  • 419
  • 2
  • 7
  • 23
0

You can try in this way and Async functions itself returns a promise, you don't need to return a new Promise manually.

async componentDidMount() {
   try {
     /*To be prepared to attach JWT token*/
     axios.interceptors.request.use(req => req);

     const getArticles = async () => { 
       try {
         const data = axios.get('https://xxxxx/api/articles');
         this.setState({ errorOnArticlesLoading: false, articles: data.data.items });
       } catch (err) {
         this.setState( {errorOnArticlesLoading:true} );
       }
     };
     await getArticles()
  } catch(err) {
    console.log('Handled root error')
 }
}
Naren
  • 4,152
  • 3
  • 17
  • 28
  • Thanks for your answer, but it returns one more uncaught Error in case user is not logged in. Corrected with an additionnal await right before 'axios.get'. And the initial axios error (Bad request) is still in the console. – Grégory C Oct 31 '20 at 13:30
  • Updated with `root` `try catch` which will prevent the error in console. – Naren Oct 31 '20 at 14:48
  • I tried but the Bad Request Error still reaching the console as if it wasn't cacheable by a try/catch block. Thanks for efforts – Grégory C Oct 31 '20 at 14:57
  • 1
    Can you create a stackblitz for it, not able to check with given code, there must something wrong in your code. – Naren Oct 31 '20 at 15:09