[英]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.