axios响应拦截器错误处理及思想

axios响应拦截器错误处理及思想

最后修改时间:6 months ago

# axios的拦截器分为两部分(以后源码还是要读的)

  1. 服务器状态为300以下
  2. 服务器状态为300+
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 服务器状态为300以下

走response拦截器在其中判断,刨析res.code来判断

    const res = response.data
    // console.log(res);
    // 如果自定义代码不是20000,则判断为错误.
    if (res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      
      // 50008: 非法token; 50012: 其他客户端已登录; 50014: Token 已过期;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('您已注销,可以取消以停留在此页面,或重新登录', '确认注销', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 服务器状态为300+

走ERROR 这里会直接返回一个error对象(error对象比较特殊但是也可以(.)) 如果想在拦截器中处理就要用error.response即可打印http数据包 不过一般都是直接返回catch单一处理问题

  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
1
2
3
4
5
6
7
8
9
axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- 全文完 -

留下一条留言?
默认颜色

主题颜色

标准颜色

更多颜色...