我们正在使用 Angular 5 和 Spring 2 OAuth 后端。 现在,当我发送旧 token 时,它当然已经过期了。它返回状态代码:401 以及带有无效 token 的错误响应等。现在我无法在日志中或当我捕获错误时看到它。我想要获取错误,以便我可以首先记录它,然后刷新 token 或将其发送到登录页面。
现在,如果我订阅该请求:
.subscribe(res => {
//just random stuff.
}, err => {
console.log("error", err);
});
I just see this response in the log with an unknown error like in this image
会不会是后端故障?因为我还在日志中看到类似“不存在‘Access-Control-Allow-Origin’ header ”的错误,尽管这是因为 token 无效。
Although I can see this response code in Google Chrome Dev Tools 和 401 状态代码。
所以我尝试自己寻找解决方案。我已经有了一个拦截器并尝试了一些解决方案
return next.handle(authReq)
.catch(error => {
console.log("im in here");
console.log(error);
return Observable.throw(error);
});
Http 服务只是抛出一个错误,catch 不是一个函数,甚至没有记录错误或“我在这里”。
我也尝试过在 next.handle 之后使用 .do,但遇到了与 catch 相同的错误
.do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (err: any) => {
console.log(err);
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
}
}
});
我在 http.get 之后尝试过使用管道,但它也不起作用。
http.get(...).pipe(
retry(3), // retry a failed request up to 3 times
catchError(this.handleError) // then handle the error
);
最佳答案
import 'rxjs/add/operator/catch';
Somefunc(){
this.httpClient
.get("data-url")
.subscribe(
data => console.log('success', data),
error => console.log('oops', error)
);
}
OR
this.httpClient
.get("data-url")
.catch((err: HttpErrorResponse) => {
// simple logging, but you can do a lot more, see below
console.error('An error occurred:', err.error);
});
应该可以。
关于javascript - Angular 5 HttpClient 错误响应无法捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49512189/