简体   繁体   中英

ReactJS - Javascript try/catch shows an error in the console

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} );
        });
}

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')
 }
}

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} );
        });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM