【问题标题】:Argument of type 'HttpErrorResponse' is not assignable to parameter of type'HttpErrorResponse' 类型的参数不可分配给类型参数
【发布时间】:2021-08-16 16:42:48
【问题描述】:

我正在尝试让全局 HTTP 拦截器工作。

我们有两个拦截器,一个用于客户端错误,一个用于服务器端错误。

我想尝试抛出一个 HttpErrorResponse 类型的错误,以便客户端错误捕获器不会拾取此错误。

但是,TypeScript 编译器会抛出以下错误:

Error: errors/http-error.interceptor.ts:26:37 - error TS2345: Argument of type 'HttpErrorResponse' is not assignable to parameter of type '{ error?: any; headers?: HttpHeaders | undefined; status?: number | undefined; statusText?: string | undefined; url?: string | undefined; }'.
  Types of property 'url' are incompatible.
    Type 'string | null' is not assignable to type 'string | undefined'.
      Type 'null' is not assignable to type 'string | undefined'.

26         throw new HttpErrorResponse(error);
                                       ~~~~~

我已经尝试调整参数的类型和返回类型。

我哪里错了?

import {
  HttpHandler,
  HttpRequest,
  HttpEvent,
  HttpErrorResponse,
  HttpInterceptor
} from "@angular/common/http";
import { Injectable } from '@angular/core';
import { Observable } from "rxjs";
import { catchError } from "rxjs/operators";
import { SnackbarService } from "../services/snackbar.service";

@Injectable({
  providedIn: 'root'
})
export class HttpErrorInterceptor implements HttpInterceptor {
  constructor(private snackbarService: SnackbarService) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        this.snackbarService.openError(`An error has occurred. Status: ${error.status}\nMessage: ${error.message}`);
        throw new HttpErrorResponse(error);
      })
    );
  }
}

【问题讨论】:

  • 为什么要创建一个新实例?只需throw error;

标签: angular angular-http-interceptors


【解决方案1】:

catchError 是一个 rxjs 操作符,它期望你返回并且 Observable 不仅仅是抛出一个普通的 JavaScript 错误。你应该做的是使用另一个 rxjs 运算符throwError 并像这样返回它 return throwError(error);

如果您不想进一步处理错误并且只显示您的通知,您也可以只返回一个空的 Observable。

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 2021-06-14
    • 2018-08-10
    • 2021-02-03
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多