【发布时间】:2022-01-15 23:47:11
【问题描述】:
这是我的错误拦截器类。我需要向 ccomponent 类 observable 方法抛出错误错误: 我检查过throwError(error) is now deprecated, but there is no new Error(HttpErrorResponse)
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private toastr: ToastrService,private authService: AuthService,
private router:Router) {
}
intercept( request: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
catchError((error: HttpErrorResponse) => {
debugger
let message = '';
if (error.error instanceof ErrorEvent) {
// handle client-side error
message = `Error: ${error.error.message}`;
this.toastr.error(message);
} else {
// handle server-side error
debugger
message = `Error: ${ error?.error?.Message || error?.statusText}`;
if(!error.status)
{
this.toastr.error('Not able connect to server');
}
else if ([400].includes(error.status) && error.error?.Message === 'Session Expired') {
this.toastr.error("Session Expired");
this.authService.logout();
}
.....
else if ([404].includes(error.status)) {
this.router.navigate(['404']);
}
else
{
this.toastr.error(message);
}
}
return throwError(() => error) //If i throw errror like this it is coming error inteceptor agian
})
)
}
}
组件
getEditCollectionById(id:string)
{
debugger
this.collectionService.getEditCollectionById(id).pipe(takeUntil(this.unsubscribe$)).subscribe({
next: (result: any) => {
if (result) {
this.collection=result;
}
else {
this.close();
}
},
error: (error:any) => {
// If i throw error in interceptor it is not coming here
this.goToDetail(this.collectionId);
}
});
}
服务
getEditCollectionById(id: string): Observable<ICollection> {
return this.httpClient.get<Result<ICollection>>(baseUrl + '/Collection/GetEditCollectionById'+ `/${id}`)
.pipe(map((res:any)=>{ res.data.valueDate = new Date(res.data.valueDate);
return res.data;
})
);
}
我需要在拦截器类中抛出错误。我从服务器收到 400 错误。我需要显示来自拦截器类的错误消息,我需要向控制器方法抛出错误。
编辑:
错误调试
编辑:调试后发现它的发生是因为
logout() {
debugger
this.httpClient.post<any>(`${baseUrl}/Auth/revoke-token`, {}, { withCredentials: true })
.subscribe();
this.stopRefreshTokenTimer();
this.setUserValue(null);
this.router.navigate(['login']);
}
我需要在这个方法中进行更新吗?
【问题讨论】:
标签: angular typescript rxjs