javascript - 如何全局捕获 axios 错误并有时能够推翻它们
问题描述
目前我正在使用响应拦截器instance.interceptors.response.use
进行全局错误处理。在那个函数中,我在 404 的情况下重定向,我在 401 等情况下清除存储。效果很好:)
除了现在我有一个地方我想以不同的方式处理 404 错误,但是一个简单的 try/catch 或 .catch 将不起作用,因为 axios 拦截器会拦截响应并立即重定向。
在这种情况下,最佳做法是什么?
- 不使用拦截器进行全局错误处理?(但是然后呢?在每个请求之后调用一个handleError类型的函数,除了这个?)
- 以某种方式暂时关闭它
- 通过axios请求传递一个ignore404选项或其他东西(虽然我每个请求都使用一个函数所以我不能这样做很简单)
- 什么是最好的,但我不确定 axios 是如何总是做一些全局错误报告,除非你自己捕获它。在那个时候,如果我想的话,我可以让全局错误处理程序完成它的工作
我的拦截器:
function onResponseRejected(error) {
const { response } = error;
if (!response) return Promise.reject(error); // network error, not axios related
const { status } = response;
const { errors } = response.data;
if (status === 403) {
router.push({ name: '403' });
} else if (status === 404) {
router.push({ name: '404' });
}
....
....
我的 axios 请求
export const fetch = (some) => {
return get(`some/${someId}/url/`)
}
我的应用程序对请求的使用
const response = fetch(this.$route.params.connectorId, this.$route.params.mapperId).catch(() => {
console.log('At this moment the request will be redirected to another route...');
});
解决方案
推荐阅读
- html - 在两个路由器插座中显示相同的组件
- javascript - 如何在嵌套路由中渲染组件
- google-kubernetes-engine - Anthos MCI:如何在 GKE 中为 redirectToHttps 注释应用 FrontendConfig
- javascript - Symfony / Mercure / JS EventSource 不发送 cookie
- c++ - Qt5:Windows 10 标题栏自定义期间的 Aero Snap
- r - 使用 R 中的分隔符将具有不同长度且没有模式的文本列拆分为多列
- javascript - 选择时的角度类型错误
- java - folder.listfiles() 在 android 11 中返回 null
- r - 返回一行第二大值的列名
- python - SQL:如果存在则更新现有值。使用参数化查询 (?)