[英]Axios Interceptors and Try/Catch error handling
在我的 React Native 應用程序中,我在try/catch
塊中處理對 api 的每次調用,並且還使用axios interceptors
來處理我從服務器獲得的錯誤。
問題是同時使用它們似乎是多余的,因為我已經使用axios interceptors
處理錯誤並且不需要catch
塊。 然而,刪除try/catch
塊會導致UnhandledPromiseRejectionWarning
。
try/catch
api 調用:(將刪除 CONSOLE.LOG )
// Request to the server
const handleSubmit = async () => {
try {
const response = await axis.post('API_URL',{BODY});
return response.data
} catch (error) {
console.log(error);
}
};
axios interceptors
:
// Intercept on response
axios.interceptors.response.use(
res => {
return res;
},
err => {
// Error handling logic
// ....................
return Promise.reject(err);
},
);
有什么方法可以讓我繼續在我的函數中使用try/catch
並仍然使用 axios axios interceptors
處理錯誤,或者只使用axios interceptors
並避免UnhandledPromiseRejectionWarning
?
你可能已經明白了這一點,但我會嘗試提供一些意見。
如果你像return Promise.reject(err)
那樣做,那么err
object 將被發送到你的catch
方法。 如果沒有catch
,錯誤將被拋出到控制台。
如果您只是使用return err
或任何其他值,該值將返回到then
或await
方法/變量。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.