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

为axios配置拦截器 #21

Closed
Mistariano opened this issue Apr 16, 2020 · 1 comment · Fixed by #32
Closed

为axios配置拦截器 #21

Mistariano opened this issue Apr 16, 2020 · 1 comment · Fixed by #32
Assignees
Labels
Projects
Milestone

Comments

@Mistariano
Copy link
Contributor

配置axios拦截器,每次req发送网络请求后可以在拦截器中自动捕获并格式化处理网络错误

将网络错误重新封装为

{code: xxx, err: xxx}

的形式并返回,其中code是网络错误码40x或50x,err是原本抛出的异常或错误信息

see https://www.jianshu.com/p/a0c67f4e145e

@Mistariano Mistariano added this to TODO in alpha dev via automation Apr 16, 2020
@Mistariano Mistariano added this to the alpha dev milestone Apr 16, 2020
@luo-junyu luo-junyu moved this from TODO to WIP in alpha dev Apr 18, 2020
@sinoyou
Copy link
Contributor

sinoyou commented Apr 20, 2020

实现:

使用axios.creator创建实例instance,为其添加了回复拦截器,用于封装错误代码和错误信息。而后将instance放入原本的req函数中,req函数的接口形式不变。

行为

当Promise被resolve时,将正常返回response对象(为promise,需要.then执行)
当Promise被rejected时,将返回Promise.rejected对象,其value为{error: 错误代码, response: 错误回复本体}(可用.catch捕捉)

400: 客户端请求有语法错误
401: 请求未经授权
404: 页面未找到
403: Bad Gateway
500: Server Error
-1: 不常见错误

测试

正常访问:能够通过Jsonplaceholder网站的请求接口。
错误访问:访问本地的未知页面,能够按约定返回rejcted对象。
测试问题:受限CORS,向不存在的网页发请请求时,会先调用preflight进行OPTION查询,在本体运行前已经被预先拦截了,尝试解决未果。

close #21

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
No open projects
alpha dev
  
DONE
Development

Successfully merging a pull request may close this issue.

2 participants