角度拦截器不应该拦截错误的请求



我正在用Angular 8编写一个Web应用程序,它从.NET Core后端获取数据。它使用 JWT 令牌进行身份验证,如果令牌无效,后端会给出401 Not Authorized错误代码。为了在 Angular 中正确处理这个问题,我添加了一个 http 拦截器:

import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse,
HttpResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import {catchError, finalize, first, tap} from 'rxjs/operators';
import {AuthenticationService} from "../_services/authentication.service";
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).observ((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;
console.log("Hij komt als allerlaatste hier, waar de error");
console.log(error);
});
}
}

目前,这是正确的。但是,我正在添加一个注册页面,如果电子邮件已在使用中,用户应该会收到错误。然后后端给出一个带有状态代码400 Bad Request的响应,但我想在我发送请求的地方自己的代码中收到此错误,以正确处理用户消息。

我尝试使用 tap((,但错误的请求错误被 catchError 函数捕获为错误。

我应该如何正确解决此问题?

您可以使用rxJs中的throwError(),所以如果响应400,您只需抛出错误并在service中捕获它,所以只需再添加 1 个 if 条件,用于错误代码Bad Request400

if (err.status === 400) {
const error = err.error.message || err.statusText;
return throwError(error);
}

相关内容

最新更新