【发布时间】:2020-07-13 05:34:55
【问题描述】:
我正在开发 Angular 8
我正在尝试通过 Interceptor 集中错误处理
我的拦截器代码正在运行,但没有返回任何错误
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpResponse,
HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { RestService } from './restservice';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private rest : RestService , private route : Router){}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// console.log('jcsjdsjd');
// console.error('xjxfjb');
// console.log(request);
// console.log(next);
return next.handle(request).pipe(catchError(err => {
console.log(err);
if (err.status === 401) {
// auto logout if 401 response returned from api
// this.authenticationService.logout();
location.reload(true);
}
const error = err.error.message || err.statusText;
return throwError(error);
}))
}
}
我还在app.module.ts的Providers中定义了拦截器
providers: [RestService , AuthGuard , commonRest , {
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorInterceptor,
multi: true
}],
我收到错误 403 的请求的响应是:
{
"messagecode": 403,
"message": "not valid token!"
}
【问题讨论】:
-
您是否尝试过使用 tap() 方法并检查是否 (err instanceof HttpErrorResponse) ?
-
@BrianDucca 你能分享一个使用 tap() 的虚拟代码
-
当然:
return next.handle(request).pipe( tap(() => {},(err: any) => { if (err instanceof HttpErrorResponse) { if (err.status === 401) { //do your thing } } }));并添加 importimport {tap} from 'rxjs/operators'; -
@BrianDucca 我用你的代码试过了 ->>>> 拦截(请求:HttpRequest
,下一个:HttpHandler):Observable > { console.log(request);控制台.log(下一个); return next.handle(request).pipe( tap(() => {},(err: any) => { console.log(err); if (err instanceof HttpErrorResponse) { console.log(err); if ( err.status === 401) { console.log("这是 401"); } } })); } >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>> 但是 next.handle(request) 中的控制台在错误 403 上没有返回任何内容 -
也许问题是你如何在你的 api 中返回你的错误?在我的情况下,该代码运行良好,我有一个 spring-boot API (Java) 和 Angular 8 前端应用程序。你的 api 是用什么做的?
标签: angular angular8 angular-httpclient angular-http-interceptors