使Axios Catch()函数在其他组件中可重复使用
我最近阅读这个问题< /a>,想在我的情况下提出一个更具体的问题。
我的应用程序中有许多不同的Axios组件,这些组件在the()函数中的表现都有所不同。但是,我具有普遍的捕获()函数,并且发现自己在每个AXIOS功能中都重复了这个巨大的代码块。当然,这似乎并没有很好地遵循干燥的原则。
有没有一种方法可以创建一个可以重复使用的更灵活的Axios组件,或者只是避免粘贴到处的catch()块的一种方法?
axios
.patch/delete/get/post(
"API ROUTE URL",
{
withCredentials: true,
}
)
.then(function (response) {
// stuff like...
// setDrafts(response.data.results);
// setState(response.data);
// alert(message);
})
.catch(function (error) {
// this portion is the same universally
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
toast.error(
`ERROR ${error.response.status}:
See console log for more info and please report this incident`,
{
duration: 4000,
position: 'bottom-center',
}
);
console.log(error.config);
});
I recently read this question and wanted to ask a more specific question in my scenario.
I have many different axios components in my app, which all behave a bit differently in the then() function. However, I have a universally same catch() function, and I found myself repeating this huge code block in every axios function I have. This, of course, didn't seem to follow the DRY principle very well.
Is there a way to create a more flexible Axios component I can reuse, or just a way to avoid pasting the catch() block everywhere?
axios
.patch/delete/get/post(
"API ROUTE URL",
{
withCredentials: true,
}
)
.then(function (response) {
// stuff like...
// setDrafts(response.data.results);
// setState(response.data);
// alert(message);
})
.catch(function (error) {
// this portion is the same universally
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
toast.error(
`ERROR ${error.response.status}:
See console log for more info and please report this incident`,
{
duration: 4000,
position: 'bottom-center',
}
);
console.log(error.config);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需创建一个
捕获函数
,然后在任何需要的地方重复使用即可。Simply create a
catch function
and reuse it wherever you want.