【发布时间】:2017-08-31 18:38:17
【问题描述】:
我正在使用vue-resource 从服务器获取数据。用户需要拥有 JWT 令牌才能获取正确的数据。如果令牌无效或过期,则返回 401 状态。如果用户尝试访问禁止页面,则返回 403。
我想捕获这些错误并适当地处理它们(全局)。这意味着,调用应该完全由拦截器处理(如果是 401、403)。
如何防止浏览器消息“未捕获(承诺中)”并创建一些全局错误处理?我不想在每次调用时都有一个本地错误处理程序。
我有以下拦截器:
Vue.http.interceptors.push(function (request, next) {
request.headers.set('Authorization', Auth.getAuthHeader());
next(function (response) {
if (response.status === 401 || response.status === 403) {
console.log('You are not logged in or do not have the rights to access this site.');
}
});
});
以及 Vue 中的以下调用 methods:
methods: {
user: function () {
this.$http.get('http://localhost:8080/auth/user').then(function (response) {
console.log(response);
});
}
}
【问题讨论】:
-
看起来您已经在拦截器中处理错误响应。您不想向调用者隐藏失败的响应/承诺,否则看起来一切正常。我不会担心控制台错误,大多数用户不会看到它们
-
@Phil,感谢您的回复。当
then()中没有捕获到异常时,是否没有副作用?我通常会尽量防止浏览器错误(HTTP 错误除外)。
标签: javascript promise vue.js interceptor vue-resource