Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Taro.request Promis后异常处理 #3017

Closed
power721 opened this issue May 12, 2019 · 3 comments
Closed

Taro.request Promis后异常处理 #3017

power721 opened this issue May 12, 2019 · 3 comments

Comments

@power721
Copy link

问题描述
调用Taro.request使用Promis后,服务端返回错误,onrejected无效。

复现步骤

Taro.request({
      url: 'https://college.nightcoder.club/majors',
      method: 'POST',
      data: data,
    }).then(res => {
      // do something
  }).catch(error => {
      // 无效
      Taro.showToast({
        title: error,
        icon: 'none'
      });
  });

期望行为
将服务端异常转换为Promise rejection。

报错信息

系统信息

Taro v1.2 及以上版本已添加 taro info 命令,方便大家查看系统及依赖信息,运行该命令后将结果贴下面即可。

  • 操作系统: Linux 4.15 Linux Mint 19.1
  • Taro 版本 v1.2.13
  • Node.js 版本 10.15.1
  • 报错平台 weapp

补充信息

@taro-bot
Copy link

taro-bot bot commented May 12, 2019

欢迎提交 Issue~

如果你提交的是 bug 报告,请务必遵循 Issue 模板的规范,尽量用简洁的语言描述你的问题,最好能提供一个稳定简单的复现。🙏🙏🙏

如果你的信息提供过于模糊或不足,或者已经其他 issue 已经存在相关内容,你的 issue 有可能会被关闭。

Good luck and happy coding~

@Garfield550
Copy link
Collaborator

我认为这不应该是 Request 方法做的事情,即使什么 Axios 这样的库它做了。
如果 Taro 改了这个行为,这会和微信小程序的 Request 行为不一致,有可能会导致使用 Taro 的开发者大幅重构。

你可以看看这篇简书文章提到的关于 wx.request 的行为:

wx.request是一个基础的api,fail只发生在系统和网络层面的失败情况,比如网络丢包、域名解析失败等等,而类似404、500之类的接口状态,依旧是调用success,并体现在statusCode上。

所以我建议在 then 里面判断 statusCode 的方式去处理服务器的异常。
或者使用 async/await 的写法,比如

try {
  const res = await Taro.request({});
  if (res.statusCode === 500) {
    throw new Error('Internal server error');
  }
}

实在不想每个都这么写就自己封装一下 Taro.request()

public static async Request<T = any, U = any>(
  params: Services.Http.Request.Params<U>
): Promise<Services.Http.Request.Promised<T>>

@power721
Copy link
Author

OK, got it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants