首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用vue-resource截取承诺错误

使用vue-resource截取承诺错误
EN

Stack Overflow用户
提问于 2019-09-26 02:07:20
回答 1查看 555关注 0票数 0

我想用下面的代码在我的main.js中截获代码为!= 200的所有api响应,分派一个操作,然后显示一个显示错误消息的toast。我使用的是vue-resource,我的拦截器如下:

代码语言:javascript
复制
Vue.http.interceptors.push(function(request, next) {
  next(function(response) {
    debugger;

    if (response.status != 200) {
      store.dispatch("errorAction", response);
    }
  });
});

但是回调中的代码永远不会被访问到...

我的api调用是这样完成的。java控制器只是抛出一个异常,错误代码为500。

代码语言:javascript
复制
 Vue.http
    .get(`http://${ADDRESS}/${store.state.module}/foo/exception`)
    .then(() => {}, () => {});

我是Promises的新手,可能会把事情搞得一团糟,但我不想给每个promise都传递一个错误回调。如果我的请求如下:

代码语言:javascript
复制
export function getFoo(cb) {
  Vue.http
    .get(`http://${ADDRESS}/${store.state.module}/foo`)
    .then(
      response => {
        return response.json();
      },
      () => {}
    )
    .then(foos => {
      cb(foos);
    });
}

我想去掉() => {},并使用拦截器代码来运行。

EN

回答 1

Stack Overflow用户

发布于 2019-10-02 03:45:46

我想我也遇到过同样的问题,所以我试着查看了文档。嗯,这很简单,你只需要这样做:

在main.js中

代码语言:javascript
复制
Vue.http.interceptors.push(function(req) {

//Here you can add some headers, if needed
req.headers.set('awesomeHeader', 'owwnt')

return function(res) {

    if( res.status == 200 || res.status == 201 || res.status == 202 ){ //Here you add the status codes that you'll work with, just like my example
        //Sucess response
    } else {
        //Every time witch an request return a status differ form the list above, you can do whatever you want, for example you can redirect the page for a new one
        window.location.href = `http://localhost:8080/#` 
        //If you want to display a notification, you need to import the component before, and then do something like it:
        Notification.success({
             title: 'error',
             message: 'Unauthorized request!',
             offset: 100
         })
    }

};
})

它回答你的问题了吗?我希望是这样。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58104245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档