[英]Axios Interceptors and Try/Catch error handling
In my React Native app, I handle each call to the api within a try/catch
block and am also using axios interceptors
to handle the errors that I get from the server.在我的 React Native 应用程序中,我在
try/catch
块中处理对 api 的每次调用,并且还使用axios interceptors
来处理我从服务器获得的错误。
The problem is that using both of them seems redundant since I'm already handling the errors with axios interceptors
and have no need of the catch
block.问题是同时使用它们似乎是多余的,因为我已经使用
axios interceptors
处理错误并且不需要catch
块。 Yet removing the try/catch
blocks result in an UnhandledPromiseRejectionWarning
.然而,删除
try/catch
块会导致UnhandledPromiseRejectionWarning
。
try/catch
for api calls: ( WILL REMOVE THE CONSOLE.LOG ) 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
: axios interceptors
:
// Intercept on response
axios.interceptors.response.use(
res => {
return res;
},
err => {
// Error handling logic
// ....................
return Promise.reject(err);
},
);
Is there any way I can keep using try/catch
in my functions and still handle the errors with axios interceptors
or just use axios interceptors
and avoid the UnhandledPromiseRejectionWarning
?有什么方法可以让我继续在我的函数中使用
try/catch
并仍然使用 axios axios interceptors
处理错误,或者只使用axios interceptors
并避免UnhandledPromiseRejectionWarning
?
You might have already figured this out, but I'll try to give some input.你可能已经明白了这一点,但我会尝试提供一些意见。
If you do as you have return Promise.reject(err)
then the err
object will be sent to your catch
method.如果你像
return Promise.reject(err)
那样做,那么err
object 将被发送到你的catch
方法。 If no catch
is present the error will be thrown to the console.如果没有
catch
,错误将被抛出到控制台。
If you instead just use return err
or any other value, that value will be returned to the then
or await
method/variable.如果您只是使用
return err
或任何其他值,该值将返回到then
或await
方法/变量。
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.