簡體   English   中英

ReactJS - Javascript try/catch 在控制台中顯示錯誤

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

我對 React 還很陌生,現在我正在學習這門語言。 為此,我正在構建一個測試項目,我嘗試在該項目上遇到主要的經典問題並尋求解決它。

對於大多數 React 開發者來說,遵循代碼沒有任何困難,但我會提供一些細節以便更好地理解。

我有一部分 javascript 代碼從 Symfony 后端 API 返回文章列表,僅當用戶被授權獲取它時(稍后將通過 JWT 進行授權)。 getArticles函數返回一個 Promise,它嘗試從 Symfony 后端在try {} catch (error) {}塊中獲取文章。

自願地,不會發送授權令牌來觸發查詢中的錯誤。

由於axios.get位於try {} catch (error) {}塊內,我很驚訝控制台中出現請求的錯誤。 它不會影響行為,但在控制台中出現這些錯誤並不是很干凈。

我的問題:當代碼在try/catch時,為什么控制台中會出現錯誤? 為了獲得更干凈的應用程序行為,有沒有辦法避免在控制台中出現此錯誤? 我發現了其他 React try/catch問題,但我沒有扣除與我的問題的相似性。 我錯過了什么嗎?

提前致謝 ;-)

我知道我的代碼可以重構,不要猶豫,提出任何好的做法

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

您可以嘗試這種方式,Async 函數本身會返回一個new Promise ,您不需要手動返回一個new Promise

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

似乎沒有解決方案可以避免控制台中的 401 http 錯誤代碼,因為它是由 Chrome 本身打印的: 請參閱此處的討論 所以下面的代碼無法避免在控制台打印401錯誤狀態。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM