gpt4 book ai didi

angular - throwError(error) 现在已弃用,但没有新的 Error(HttpErrorResponse)

转载 作者:行者123 更新时间:2023-12-04 14:36:45 27 4
gpt4 key购买 nike

显然 throwError(error)现在已弃用。 VS Code 的 IntelliSense 建议 throwError(() => new Error('error') . new Error(...)只接受字符串。在不破坏我的 HttpErrorHandlerService 的情况下更换它的正确方法是什么? ?
http-error.interceptor.ts

import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpErrorResponse,
HttpResponse,
HttpHeaders
} from '@angular/common/http';
import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';

import { HttpErrorHandlerService } from '@core/services';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
private readonly APP_XHR_TIMEOUT = 6000;

constructor(private errorHandlerService: HttpErrorHandlerService) {}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(this.performRequest(request)).pipe(
timeout(this.APP_XHR_TIMEOUT),
map((event: HttpEvent<any>) => this.handleSuccessfulResponse(event)),
catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next)),
finalize(this.handleRequestCompleted.bind(this))
);
}

private performRequest(request: HttpRequest<any>): HttpRequest<any> {
let headers: HttpHeaders = request.headers;
//headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
return request.clone({ headers });
}

private handleSuccessfulResponse(event: HttpEvent<any>): HttpEvent<any> {
if (event instanceof HttpResponse) {
event = event.clone({ body: event.body.response });
}
return event;
}

private processRequestError(
error: HttpErrorResponse,
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
console.log('http error response');

if ([401].includes(error.status)) {
return throwError(error);
}

this.errorHandlerService.handle(error);

return throwError(error);
}

private handleRequestCompleted(): void {
// console.log(`Request finished`);
}
}

import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';

import { MessageService } from 'primeng/api';
import { TimeoutError } from 'rxjs';

/**
* Shows a user-friendly error message when a HTTP request fails.
*/
@Injectable({
providedIn: 'root'
})
export class HttpErrorHandlerService {
constructor(private messageService: MessageService) {}

handle(error: Error | HttpErrorResponse) {
if (error instanceof TimeoutError) {
return this.openDialog('error', `Няма връзка до сървъра.`);
}

if (error instanceof HttpErrorResponse && error.error && error.error.message) {
return this.openDialog('error', error.error.message);
}

if (error instanceof Error) {
switch (error.message) {
default:
return this.openDialog('error', `An unknown error occurred`);
}
}

// Generic HTTP errors
switch (error.status) {
case 400:
switch (error.error) {
case 'invalid_username_or_password':
return this.openDialog('error', 'Невалидно потребителско име или парола');
default:
return this.openDialog('error', 'Bad request');
}

case 401:
return this.openDialog('error', 'Ще трябва да се логнете отново');

case 403:
return this.openDialog('error', `You don't have the required permissions`);

case 404:
return this.openDialog('error', 'Resource not found');

case 422:
return this.openDialog('error', 'Invalid data provided');

case 500:
case 501:
case 502:
case 503:
return this.openDialog('error', 'An internal server error occurred');

case -1:
return this.openDialog(
'error',
'You appear to be offline. Please check your internet connection and try again.'
);

case 0:
return this.openDialog('error', `CORS issue?`);

default:
return this.openDialog('error', `An unknown error occurred`);
}
}

private openDialog(severity: string, message: string) {
if (message?.trim()) {
this.messageService.add({
key: 'interceptor',
severity: severity,
summary: 'Информация',
detail: message,
life: 3000
});
}
}
}

auth.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse
} from '@angular/common/http';
import {
BehaviorSubject,
catchError,
EMPTY,
filter,
finalize,
Observable,
switchMap,
take,
throwError
} from 'rxjs';

import { AuthService } from '@core/services';
import { AuthResponse } from '@core/types';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private refreshTokenInProgress: boolean;
private refreshToken$ = new BehaviorSubject<AuthResponse | null>(null);

constructor(private authService: AuthService) {}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next
.handle(this.performRequest(request))
.pipe(
catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next))
);
}

private performRequest(request: HttpRequest<any>): HttpRequest<any> {
const accessToken = this.authService.getAccessToken();

let headers = request.headers;
if (accessToken) {
headers = headers.set('Authorization', `Bearer ${accessToken}`);
}

return request.clone({ headers });
}

private processRequestError(
error: HttpErrorResponse,
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
console.log('auth interceptor called');

if (
error instanceof HttpErrorResponse &&
error.status === 401 &&
this.authService.isSignedIn()
) {
return this.refreshToken(request, next);
}

return throwError(error);
}

private refreshToken(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('refresh token in auth.interceptor called');

// in case the page consists of more than one requests
if (!this.refreshTokenInProgress) {
this.refreshToken$.next(null);
this.refreshTokenInProgress = true;

return this.authService.refreshToken().pipe(
switchMap((response) => {
if (response) {
this.refreshToken$.next(response);
return next.handle(this.performRequest(request));
}

this.authService.signOut();
return throwError(() => new Error("RefreshTokenFailed"));
}),
catchError((error) => {
this.authService.signOut();
return throwError(error);
}),
finalize(() => (this.refreshTokenInProgress = false))
);
} else {
// wait while getting new token
return this.refreshToken$.pipe(
filter((result) => result !== null),
take(1),
switchMap(() => next.handle(this.performRequest(request)))
);
}
}
}

最佳答案

取而代之的是:

    catchError((error) => {
this.authService.signOut();
return throwError(error);
}),
你可以试试这个:
    catchError((error) => {
this.authService.signOut();
return throwError(() => error);
}),
我无法彻底测试它,但一个简单的尝试似乎奏效了。
这是我的简单测试(使用 RxJS v7.2):
服务
  getProducts(): Observable<IProduct[]> {
return this.http.get<IProduct[]>(this.productUrl)
.pipe(
tap(data => console.log('All: ', JSON.stringify(data))),
catchError(this.handleError)
);
}

private handleError(err: HttpErrorResponse): Observable<never> {
// just a test ... more could would go here
return throwError(() => err);
}
请注意 err这是类型 HttpErrorResponse .
组件
  ngOnInit(): void {
this.sub = this.productService.getProducts().subscribe({
next: products => {
this.products = products;
this.filteredProducts = this.products;
},
error: err => this.errorMessage = err.message
});
}
在这里,我能够检索到 message错误响应中的属性并将其显示在我的 UI 中。
让我知道这是否适合您。

关于angular - throwError(error) 现在已弃用,但没有新的 Error(HttpErrorResponse),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68655492/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com