wendux / fly

:rocket: Supporting request forwarding and Promise based HTTP client for all JavaScript runtimes.
https://wendux.github.io/dist/#/language
MIT License
3.9k stars 639 forks source link

在response拦截器里reject的话,有时候能catch 到error,有时候不行 #41

Closed OccurSomething closed 6 years ago

OccurSomething commented 6 years ago

拦截器配置如下:

    fly.interceptors.response.use(
    (response) => {
      //只将请求结果的data字段返回
      console.log('fly.interceptors response=' + JSON.stringify(response.data));
      // return response.data
      return Promise.reject(new Error("heheheeh", 99))
    },
    (err) => {
      console.log('fly.interceptors: error message=' + JSON.stringify(err));
    }
  )

调用如下:

  this.$app.$def.fly.get('https://www.sojson.com/open/api/weather/json.shtml?', {
      city: '上海'
    })
    .then(function (response) {
      console.log('success result=' + JSON.stringify(response.data));
    })
    .catch(function (error) {
      console.log(error);
      console.log('error msg=' + error.message);
      console.log('error status=' + error.status);
    });

有时候能进入catch,有时候不行,打断的也是

OccurSomething commented 6 years ago

拦截器里的Promise.reject(new Error("heheheeh",99))是故意的,另外Error构造方法不能放statuscode吗?

wendux commented 6 years ago

我在本地测了一下你的case, 没有遇到过不走拦截器的情况,你可以先更新一下flyio到最新版试试。还有error对象你完全可以自定义,如:

  fly.interceptors.response.use(
      (response) => {
        //定义错误信息
        return Promise.reject({
           message:"xxxx",
           status:0
        })
      },
      (err) => {
        console.log('fly.interceptors: error message=' + JSON.stringify(err));
      }
 )
tangniyuqi commented 5 years ago

image 怎么我捕获到的格式这么乱呢 造成不能后续处理

wendux commented 5 years ago

@tangniyuqi Error打印出来是文本,实际上是一个对象。

tangniyuqi commented 5 years ago

@wendux 他的结构是什么呢,只想要里面的核心内容“未登录222!”

fly自带error处理直接就能获取错误内容,就像下面这个: fly.interceptors.response.use((response) => { let data = response.data; let statusCode = data.statusCode;

if (statusCode !== 401) { return Promise.reject(new Error('未登录3333!'));

return Promise.reject(new Error({
  message: '未登录4444!',
  status: 1111
})); 

} return response; }, (error) => { let status = error.status;

if (status === 0) { return '网络连接异常!'; } else if (status === 1) { return '网络连接超时!'; } else if (status === 401) { return '未登录!'; } else { if (error.response.data.message) { return error.response.data.message; } else { return '网络错误!请稍后再试。'; } } });

自定义的错误就不能直接打印吗?