Angular 拦截器不应该拦截不良请求
Angular interceptor should not intercept bad requests
我正在 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 Request
的条件,错误代码 400
,如下所示:
if (err.status === 400) {
const error = err.error.message || err.statusText;
return throwError(error);
}
我正在 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 Request
的条件,错误代码 400
,如下所示:
if (err.status === 400) {
const error = err.error.message || err.statusText;
return throwError(error);
}