【发布时间】: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