MST
星途 面试题库

面试题:Angular HTTP请求日志记录中如何处理错误与重试逻辑

在Angular的HTTP请求日志记录场景下,当请求发生错误时,如何在日志中详细记录错误信息,并且实现一个自动重试机制,在特定次数内尝试重新发起请求。请描述整体设计方案,包括可能涉及到的RxJS操作符以及如何结合拦截器实现该功能。
17.4万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

整体设计方案

  1. 错误信息记录:利用Angular的HTTP拦截器,在请求发生错误时捕获错误信息,并将其记录到日志中。
  2. 自动重试机制:使用RxJS操作符来实现自动重试逻辑,在特定次数内尝试重新发起请求。

涉及的RxJS操作符

  1. catchError:用于捕获HTTP请求中的错误,以便进行错误处理和日志记录。
  2. retryWhen:实现自动重试机制,根据设定的重试次数和重试条件重新发起请求。

结合拦截器实现功能

  1. 创建HTTP拦截器
import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
} from '@angular/common/http';
import { Observable, catchError, retryWhen } from 'rxjs';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error) => {
        // 记录详细错误信息到日志
        console.error('HTTP Request Error:', error);
        throw error;
      }),
      retryWhen((errors) =>
        errors.pipe(
          // 设定重试次数,例如3次
          retry(3),
          // 可以在此添加重试条件逻辑
          // 比如根据特定的HTTP状态码重试
          // filter((error) => error.status === 500)
        )
      )
    );
  }
}
  1. 注册拦截器:在app.module.ts中注册拦截器:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform - browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { HttpErrorInterceptor } from './http - error.interceptor';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpErrorInterceptor,
      multi: true,
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

通过上述步骤,当Angular的HTTP请求发生错误时,错误信息会被记录到日志中,并且会根据设定的重试次数尝试重新发起请求。